0

我在 Java 中看到了一些关于 Focus 的文档,但我并不完全了解它是如何工作的。

我试图在这个短代码中重现我的疑问,我试图在 textfield2 组件中设置焦点。我想我已经尊重了文档的要求——即组件需要可显示、可见和可聚焦(https://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html)。那么,我做错了什么?

***
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class WindowForm {
    private JFrame frame;
    private JTextField textField1;
    private JTextField textField2;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    WindowForm window = new WindowForm();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public WindowForm() {
        initialize();
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        myPanel panel = new myPanel();
        panel.setBounds(10, 11, 414, 239);
        frame.getContentPane().add(panel);
        panel.setLayout(null);

        textField1 = new JTextField("textfield1");
        textField1.setBounds(137, 93, 152, 20);
        panel.add(textField1);
        textField1.setColumns(10);

        textField2 = new JTextField("textfield2");
        textField2.setColumns(10);
        textField2.setBounds(137, 124, 152, 20);
        panel.add(textField2);

        panel.changeFocus();
    }

    public class myPanel extends JPanel{

        public void changeFocus() {
            textField2.setVisible(true);
            textField2.setFocusable(true);
            textField2.requestFocusInWindow();
        }
    }
}

我看到了一些需要在 jframe 中实现addWindowFocusListener的示例 - 但我需要将此解决方案应用于 CardLayout JPanel - 所以,我认为这行不通。

先感谢您。

4

1 回答 1

0

我在 actionPerformed 块中使用 requestFocusInWindow 解决了。

像这样:


public void actionPerformed(ActionEvent e) { String command = e.getActionCommand();

if(command.equals("btnNext")) {
    cardLayout.show(nextJPanel, "Panel2");
    textField2.requestFocusInWindow();
}           

}


还有其他解决方案吗?

于 2020-06-11T18:59:09.013 回答