【发布时间】:2009-09-15 06:03:37
【问题描述】:
我在 Java 中使用 Swing 创建了一个表单。在表单中,我使用了JTextField,每当我按下一个键时,我都必须在它上面设置焦点。如何在 Swing 中设置对特定组件的关注?
【问题讨论】:
我在 Java 中使用 Swing 创建了一个表单。在表单中,我使用了JTextField,每当我按下一个键时,我都必须在它上面设置焦点。如何在 Swing 中设置对特定组件的关注?
【问题讨论】:
Component.requestFocus() 会给你你需要的吗?
【讨论】:
requestFocus(),“不鼓励使用此方法,因为它的行为取决于平台。相反,我们建议使用 requestFocusInWindow()。如果您想了解更多信息有关焦点,请参阅 Java 教程中的部分 How to Use the Focus Subsystem。”
这行得通..
SwingUtilities.invokeLater( new Runnable() {
public void run() {
Component.requestFocus();
}
} );
【讨论】:
现在我们已经搜索了 API,我们需要做的就是阅读 API。
根据 API 文档:
"因为这个的焦点行为 方法依赖于平台, 强烈建议开发人员 使用 requestFocusInWindow 时 可能的。 "
【讨论】:
请注意,由于某种原因,上述所有操作在 JOptionPane 中都失败了。经过多次试验和错误(无论如何,超过上述 5 分钟),这就是最终奏效的方法:
final JTextField usernameField = new JTextField();
// ...
usernameField.addAncestorListener(new RequestFocusListener());
JOptionPane.showOptionDialog(this, panel, "Credentials", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null);
public class RequestFocusListener implements AncestorListener {
@Override
public void ancestorAdded(final AncestorEvent e) {
final AncestorListener al = this;
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final JComponent component = e.getComponent();
component.requestFocusInWindow();
component.removeAncestorListener(al);
}
});
}
@Override
public void ancestorMoved(final AncestorEvent e) {
}
@Override
public void ancestorRemoved(final AncestorEvent e) {
}
}
【讨论】:
你也可以用JComponent.grabFocus();也一样
【讨论】:
requestFocusInWindow() 方法,该方法已在其他答案中提及。