Swing —— 限制JTextArea唯其如此输入浮点数
|
下面是示例代码: |
[复制源代码] |
class JTextFieldFilterextends PlainDocument { public static final StringFLOAT = "0123456789."; protected String acceptedChars = null; protected boolean negativeAccepted =false;
public JTextFieldFilter() { this(FLOAT); }
public JTextFieldFilter(String acceptedChars) { this.acceptedChars = acceptedChars; }
/** *设置是否接受负号 * * @param negativeAccepted * 是否接受负号 */ public void setNegativeAccepted(boolean negativeAccepted) { if (acceptedChars.equals(FLOAT)) { this.negativeAccepted = negativeAccepted; acceptedChars += "-"; } }
public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
//判断输入的是否为允许的字符 for (int i = 0; i < str.length(); i++) { if (!acceptedChars.contains(str)) { return; } }
//判断当前输入的是否为".",如果有了再判断前面有没有输入过 if (acceptedChars.equals(FLOAT) || (acceptedChars.equals(FLOAT +"-") && negativeAccepted)) { if (str.contains(".")) { if (getText(0, getLength()).contains(".")) { return; } } }
//判断如果支持负数,那么负号(-)必须在第一位 if (negativeAccepted) { if (str.indexOf("-") != 0 || offset != 0) { return; } }
super.insertString(offset, str, attr); } }
publicclass Main extends JFrame {
public static void main(String[] argv)throws Exception { new Main(); }
public Main() { setLayout(new FlowLayout()); JLabel lb = new JLabel("only float"); JTextField tf = new JTextField(10); getContentPane().add(lb); getContentPane().add(tf); tf.setDocument(new JTextFieldFilter(JTextFieldFilter.FLOAT)); setSize(300, 300); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } |