我将输入验证器设置为我的文本字段:
public class MyInputVerifier extends InputVerifier {
@Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
try {
BigDecimal value = new BigDecimal(text);
return (value.scale() <= Math.abs(4));
} catch (NumberFormatException nfe) {
return false;
}
}
public static class Tester extends JFrame implements ActionListener {
JTextField tf1;
JButton okBtn;
public Tester() {
add(panel(), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Tester();
}
});
}
public JPanel panel() {
JPanel panel = new JPanel();
okBtn = new JButton("Ok");
okBtn.addActionListener(this);
tf1 = new JTextField(10);
tf1.setInputVerifier(new MyInputVerifier());
panel.add(tf1);
panel.add(okBtn);
return panel;
}
@Override
public void actionPerformed(ActionEvent e) {
MyInputVerifier inputVerifier = new MyInputVerifier();
if (e.getSource() == okBtn) {
if (inputVerifier.verify(tf1)) JOptionPane.showMessageDialog(null, "True");
else JOptionPane.showMessageDialog(null,"False");
}
}
}
}
我55555
在文本字段中输入,它显示true
,为什么?