How to Set Focus on JTextField?

后端 未结 10 1839
感情败类
感情败类 2020-11-30 07:34

I make my game run without mouse so using pointer is not a choice. High Score menu will show when player lose.

this is my code

    highScore=new MyTe         


        
相关标签:
10条回答
  • 2020-11-30 08:11

    This code mouse cursor “jtextfield” “Jcombobox” location focused

     try {
         Robot  robot = new Robot();
            int x = Jtextfield.getLocationOnScreen().x;
            int y=  Jtextfield.getLocationOnScreen().y;
           JOptionPane.showMessageDialog(null, x+"x< - y>"+y);// for I location see
            robot.mouseMove(x, y);
        } catch (AWTException ex) { 
            ex.printStackTrace();
        } 
    
    0 讨论(0)
  • 2020-11-30 08:13

    If you want your JTextField to be focused when your GUI shows up, you can use this:

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

    Where f would be your JFrame and in is your JTextField.

    0 讨论(0)
  • 2020-11-30 08:13

    In my case nothing above worked untill I called requestFocus() AFTER my constructor has returned.

    MyPanel panel = new MyPanel(...);
    frame.add(panel);
    panel.initFocus();
    

    MyPanel.initFocus() would have:

    myTextField.requestFocus();
    

    And it works.

    0 讨论(0)
  • 2020-11-30 08:13

    While yourTextField.requestFocus() is A solution, it is not the best since in the official Java documentation this is discourage as the method requestFocus() is platform dependent.

    The documentation says:

    Note that the use of this method is discouraged because its behavior is platform dependent. Instead we recommend the use of requestFocusInWindow().

    Use yourJTextField.requestFocusInWindow() instead.

    0 讨论(0)
提交回复
热议问题