我使用Java的Swing创建了一个表格。在表格中,我使用了JTextField
,每当我按键时都必须将焦点设置在上面。如何在Swing中将焦点设置在特定的组件上?
这将起作用。
SwingUtilities.invokeLater( new Runnable() {
public void run() {
Component.requestFocus();
}
} );
既然我们已经搜索了API,现在我们只需要读取API即可。
根据API文档:
“由于该方法的焦点行为取决于平台,强烈建议开发者尽可能使用requestFocusInWindow。”
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()
方法,该方法已在其他答案中提到。 - Oleg Estekhin
requestFocus()
方法的使用不被建议,因为其行为依赖于特定平台。相反,建议使用requestFocusInWindow()方法。如果您想了解更多关于焦点的信息,请参阅The Java Tutorial中的How to Use the Focus Subsystem一节。 - Adam Mackler