所以我有文本字段,我需要为它们创建接口。
我有textfield1的KeyListener,只允许在textfield中输入整数值,但是我需要为我拥有的每个文本域创建接口
textfield1.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!((c >= '0') && (c <= '9') ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))) {
getToolkit().beep();
e.consume();
}
}
});
答案 0 :(得分:0)
为什么不将KeyAdapter
存储在变量中,然后传递变量?
KeyAdapter adapter = new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!((c >= '0') && (c <= '9') ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))) {
getToolkit().beep();
e.consume();
}
}
};
someTextField.addKeyListener(adapter);
someOtherTextField.addKeyListener(adapter);
或者,如果你很懒,你不想多次写addKeyListener
,
Stream.of(textField1, textField2, textField3).forEach(x -> x.addKeyListener(adapter));