用于文本字段的Java接口

时间:2018-02-25 09:13:59

标签: java

所以我有文本字段,我需要为它们创建接口。

我有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();
                  }
                }
              });

1 个答案:

答案 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));