如何将重点放在JTextField上?

Ken*_*iro 29 java swing jtextfield setfocus

我让我的游戏没有鼠标运行所以使用指针不是一个选择.当玩家输球时,高分菜单会显示.

这是我的代码

    highScore=new MyTextField("Your Name");
    highScore.addKeyListener(this);
    highScore.setFont(font);
    highScore.requestFocusInWindow();
Run Code Online (Sandbox Code Playgroud)

我试过了

highScore.setFocusable(true);
highScore.requestFocusInWindow();
highScore.requestFocus(true);
highScore.requestFocus();
Run Code Online (Sandbox Code Playgroud)

但仍然没有把重点放在我的身上JTextField.

如何关注它?

Luk*_*uth 50

如果您希望JTextField在GUI出现时集中注意力,可以使用:

in = new JTextField(40);
f.addWindowListener( new WindowAdapter() {
    public void windowOpened( WindowEvent e ){
        in.requestFocus();
    }
}); 
Run Code Online (Sandbox Code Playgroud)

哪个f是你的JFrame,in是你的JTextField.


mKo*_*bel 7

如果只有一个顶级容器,那么GUI构造函数中的最后一行将是例如

.
.
.
myFrame.setVisible(true);
EventQueue.invokeLater(new Runnable() {

   @Override
     public void run() {
         myComponent.grabFocus();
         myComponent.requestFocus();//or inWindow
     }
});
Run Code Online (Sandbox Code Playgroud)


小智 5

public void actionPerformed(ActionEvent arg0)
{
    if (arg0.getSource()==clearButton)
    {
        enterText.setText(null);
        enterText.grabFocus();  //Places flashing cursor on text box        
    }       
}
Run Code Online (Sandbox Code Playgroud)