如何在单击以输入键盘输出上选择文本框

时间:2016-04-28 17:45:03

标签: java swing textbox actionlistener keypad

接口

http://i.stack.imgur.com/cAvOJ.png

上图显示了我尝试实现的界面。登录面板和键盘面板需要以某种方式协同工作,所以每当我点击选定的文本框时,我都可以使用键盘输入所需的输入。

在正确的细节输入上,登录面板将更改为带有其他文本框的另一个面板,因此键盘也必须使用这些。

有什么想法吗?提前谢谢!

3 个答案:

答案 0 :(得分:1)

您可以扩展TextAction以创建每个按钮共享的ActionTextAction允许您访问最后一个重点文本组件:

Action numberAction = new TextAction()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        JTextComponent input = getFocusedComponent();
        input.replaceSelection(e.getActionCommand());
    }
};

JButton button1 = new JButton("1");
button1.addActionListener( numberAction );
JButton button2 = new JButton("2");
button2.addActionListener( numberAction );
...

你需要为" Clear"创建一个单独的Action。按钮。

答案 1 :(得分:0)

实现IMO的最佳方式是在所有JButton上setFocusable(false),因此只有两个输入字段可以成为焦点所有者。您还应该为这两个TextField配备一个FocusListener,以便您知道用户是否单击了该数字应该出现的按钮

答案 2 :(得分:0)

嗯。您可以使用JTextField跟踪当前选定的文本框,然后将FocusListeners添加到JTextFields以在foxus获得或丢失时更新当前选定的文本框。

这样的事情:

JTextField currentText;
final JTextField textField = new JTextField("Ayy");
textField.addFocusListener(new FocusListener() {

    @Override
    public void focusGained(FocusEvent e) {
        //Your code here
        currentText = textField;
    }

    @Override
    public void focusLost(FocusEvent e) {
        //Your code here
        currentText = null;
    }
});