在java中创建虚拟数字键盘

时间:2017-02-13 10:20:09

标签: java swing virtual-keyboard jpasswordfield

我正在开发桌面应用程序。在这个应用程序中,我必须使用虚拟键盘/数字键盘进行登录操作等。

我创建了一个这样的jframe: enter image description here

和按钮'创建代码是

numberButtons = new JButton[10];
    for(int i = 0; i < numberButtons.length; i++ ) {
        numberButtons[i] = new JButton(String.valueOf(i));
    numberButtons[i].setFont(new java.awt.Font("Open Sans", 0, 14));
    numberButtons[i].setPreferredSize(new java.awt.Dimension(100, 50));

    numberButtons[i].addActionListener(new ActionListener()
    {
        public void actionPerformed(java.awt.event.ActionEvent evt)
        {
            numberButtonActionPerformed(evt);
        }
    });
        numberPanel.add(numberButtons[i]);
    }

和行动方法是:

private void numberButtonActionPerformed(ActionEvent evt) {

    String currentPassword = ((JButton) evt.getSource()).getText();

    passwordField.requestFocus();
    passwordField.setText(passwordField.getText() + currentPassword);
    if (Arrays.equals(pass, passwordField.getPassword())) {
        System.out.println("Correct");
    }
}

但是调度了jpasswordfield的gettext方法。不建议使用。我有另一个想法,为每个按钮编写actionperformed方法并使用&#34; KeyEvent.VK _&#34;在每个按钮&#39;行动。但是,我认为这不是一个正确的方法。你会推荐什么?

3 个答案:

答案 0 :(得分:0)

您已使用passwordField.getPassword()。这是执行此操作的正确方法。文档说getText已被getPasswordhttps://docs.oracle.com/javase/7/docs/api/javax/swing/JPasswordField.html#getText()

取代

从返回的char[]使用this构造函数构造String。

答案 1 :(得分:0)

创建一个封装JButton的按钮类,创建侦听器以及任何其他有用的功能。然后使用该类代替按钮创建代码。

答案 2 :(得分:0)

  

但是调度了jpasswordfield的gettext方法

请勿使用setText(...)重置整个文本。

而只是将键入的字符添加到文本组件的末尾。一种方法是使用文本组件的replaceSelection(...)方法。

查看:Attaching A Single Action Listener To All Buttons了解一个有效的例子。请注意,该示例将允许您键入字符或单击按钮。