如何 Select 单击输入键盘输出的文本框

How to Select a Textbox on Click to Input Keypads Output

界面

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

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

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

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

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

像这样:

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;
    }
});

您可以扩展 TextAction 以创建一个 Action 以供每个按钮共享。 TextAction 允许您访问最后获得焦点的文本组件:

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" 按钮创建一个单独的操作。