java - JTextField 焦点

标签 java swing

我有一个框架和一个面板。我永久删除面板并添加另一个面板。添加新面板后,我需要 JTextField 来获得焦点。我该怎么做?

我尝试了 panel.requestFocus() 方法,但没有成功。

示例代码:

public class Test{
    public static void main(String[] args){

        JFrame frame = new JFrame();
        // ... frame options

        // MyPanel extends JPanel
        // and has a JTextField
        contentPane.add(new MyPanel());

        // Permanently I need to add another panel
        contentPane.removeAll();
        contentPane.add(new MyPanel());

    }
}

最佳答案

调用 panel.requestFocus() 尝试将焦点放在容器本身而不是它的任何子组件上。

使用requestFocusInWindow在将组件添加到 JFrame 之后,在 JTextField 上。在 MyPanel 中添加一个公共(public)方法来调用此方法。

避免使用requestFocus。来自docs :

requestFocus, is discouraged because it tries to give the focus to the component's window, which is not always possible. As of JDK 1.4, you should instead use the requestFocusInWindow method, which does not attempt to make the component's window focused.

public class Test {
    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame("Focus JTextField");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                MyPanel myPanel = new MyPanel();
                frame.add(myPanel);
                frame.setVisible(true);
                frame.pack();
                myPanel.focusTextField();
            }
        });
    }
}

class MyPanel extends JPanel {
    private JTextField textField;

    public MyPanel() {
        textField = new JTextField(20);
        add(textField);
    }

    public void focusTextField() {
        textField.requestFocusInWindow();
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 100);
    }
}

关于java - JTextField 焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16244349/

相关文章:

java - 如何修改camel Exchange并发送

java - 在包中运行所有测试时出现 JUnit java.lang.OutOfMemoryError

java - 访问运行时设置的变量值

java - 在新窗口的 JFrame 或 JPanel 之间切换?

java - 无法获取 JDBC 连接/事务未激活

java - HttpServletRequest.getRemoteUser() 与 HttpServletRequest.getUserPrincipal().getName()

java - 用 Java 显示 BASH 结果

java - 在java中创建我自己的paint方法

java - 设置可滚动列表的边界

java - 获取滚动金额