gpt4 book ai didi

java - JTextField 焦点

转载 作者:行者123 更新时间:2023-11-29 03:34:31 29 4
gpt4 key购买 nike

我有一个框架和一个面板。我永久删除面板并添加另一个面板。添加新面板后,我需要 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com