JTextField.requestFocus() 在向 GUI 添加按钮后停止工作

JTextField.requestFocus() stopped working after adding buttons to GUI

我有一个使用 javax.swing 和 java.awt 制作的 GUI,请求焦点致力于使文本字段保持焦点,以便用户可以从键盘开始。然后我为每个整数 0-9 添加了按钮,以及一个清除字段按钮。然而,焦点现在总是从一个按钮开始。

每当我单击一个按钮时,焦点仍然returns 到 textField,或者如果我启动焦点,它仍然在 textField 中,我该如何解决这个问题并在每次 window 打开?

示例数字按钮

JButton btn0 = new JButton("0");
        panel.add(btn0);
        btn0.setBounds(50, 360, 50, 50);
        btn0.setHorizontalAlignment(SwingConstants.CENTER);
        btn0.setForeground(Color.BLACK);
        btn0.setFont(new Font("Arial", Font.BOLD, 20));
        btn0.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String userIn = txtGuess.getText() + btn0.getText();
                txtGuess.setText(userIn);
            }
        });

文本字段代码

txtGuess = new JTextField();
        txtGuess.setBounds(325, 220, 100, 35);
        panel.add(txtGuess);
        txtGuess.setFont(new Font("Arial", Font.BOLD, 25));
        txtGuess.setHorizontalAlignment(SwingConstants.CENTER);
        txtGuess.setBackground(Color.decode("#206BA4"));
        txtGuess.setForeground(Color.decode("#EBF4FA"));
        txtGuess.setBorder(loweredBorder);
        txtGuess.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                checkGuess();
            }
        });

checkGuess()结束;

finally {
            txtGuess.requestFocus(); //sets focus to the text box after checking guess
            txtGuess.selectAll(); //highlights all text in the text field so UX is improved
            if (attempt >= 10) {
                lblOutput.setText("You lose! Try Again?");
                newGame();
            }
txtGuess.requestFocus(); 

首先你不应该使用那个方法。阅读 API 的方法,它会告诉您更好的使用方法。

how can I fix this problem and have the focus on the text field every time the window opens?

默认情况下,焦点应转到框架左上角的组件。如果这没有发生,那么你正在做一些奇怪的事情。

如果您的文本字段不是框架上的第一个组件,那么您只能在 GUI 可见后将焦点设置在它上面。

根据发布的代码,文本字段似乎位于按钮上方,因此它应该获得焦点。也许问题在于您使用的是空布局以及将组件添加到框架的顺序。如果没有适当的 MCVE,我们无法判断。

对您的代码的其他建议:

  1. 不要使用空布局和 setBounds()。您不应该手动设置大小/Swing 旨在与布局管理器一起使用。

  2. 无需为每个按钮创建唯一的 ActionListener。您可以创建一个由每个按钮共享的通用侦听器。查看: 了解此方法的工作示例。

I'm trying to figure out how to create the MCVE version to demonstrate the problem

这不是什么大谜团。你说你有一个带有文本字段的框架并且它有效。然后你添加了一个按钮,但它不起作用。所以 MCVE 将只包含一个带有文本字段和按钮的框架。游戏逻辑与您的问题无关,因此不需要。所以 MCVE 应该是大约 10 - 15 行代码。

解决方案是实施此代码

frame.addWindowFocusListener(new WindowAdapter() {
            public void windowGainedFocus(WindowEvent e) {
                textfield.requestFocusInWindow();
            }
        });