31

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 MyTextField("Your Name");
    highScore.addKeyListener(this);
    highScore.setFont(font);
    highScore.requestFocusInWindow();

I have tried

highScore.setFocusable(true);
highScore.requestFocusInWindow();
highScore.requestFocus(true);
highScore.requestFocus();

but still not gained focus on my JTextField.

How to focus it?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Kenjiro
  • 749
  • 1
  • 12
  • 33
  • Where do you add the highScore field into your GUI? Myself, I'd display a high score dialog either as a JOptionPane or JDialog or else swap GUI views via CardLayout. – Hovercraft Full Of Eels Jul 17 '11 at 10:39
  • Hm... I design my high score panel. So it look like didn't use swing. JOptionPane, JDialog. Is they can be change? CardLayout? I don't know about that. I will try. – Kenjiro Jul 17 '11 at 12:37
  • 1
    we have no idea exactly what you're doing given the limited information that you've given so far. For all we know your GUI already has a component named "highScore" inserted into it and the code above is an attempt to get a reference to it. Please provide a lot more detail and some more code so we can better help you. Otherwise we're doing nothing but guessing. Best if you can create and post an [SSCCE](http://sscce.org) that illustrates your problem. – Hovercraft Full Of Eels Jul 17 '11 at 13:03
  • Yes. I have main menu, stage, and if lose or end of the game draw pic and ask to type name to submit your score. I already solve it with my GameAction(a class that manage one keyboard type whenever its press or not. And I can virtualy press the keyboard with tap() method). So i create my GameAction that user infrequently press like F1 or € something like that. Call requestFocus when that button press(I pressed virtualy). Thx for your help. – Kenjiro Jul 17 '11 at 14:21

10 Answers10

61

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.

Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111
  • It should work then, too, but you'll need to use another method. All available methods are shown in the [`WindowAdapter`-docs](http://download.oracle.com/javase/1.4.2/docs/api/java/awt/event/WindowAdapter.html). – Lukas Knuth Jul 17 '11 at 10:54
  • hm... how about focus when i show my JTextField? What listener should i use? – Kenjiro Jul 17 '11 at 13:38
  • So your Frame is already shown and then you show up your `JTextField` (in an `onClick` event or something)? And when it shows up, it should gain the input-focus? – Lukas Knuth Jul 17 '11 at 14:03
  • Yes. I have main menu, stage, and if lose or end of the game draw pic and ask to type name to submit your score. I already solve it with my GameAction(a class that manage my keyboard type whenever its press or not. And I can virtualy press the keyboard with tap() method). So i create my GameAction that user infrequently press like F1 or € something like that. Call requestFocus when that button press(i pressed virtualy). Thx for your help. – Kenjiro Jul 17 '11 at 14:19
  • This worked for me even when `f` is not the containing component. I don't understand. I've created a `JDialog` and used `in.requestFocus();` afterwards. It didn't work. I've added a windowListener and requested focus from there then it worked. But why? Can you explain it? – WVrock Jun 19 '15 at 15:14
  • You added the windowListener to the dialog? That would be odd. My guess is, that `requestFocus()` doesn't actually do anything *immediately*, but only adds the action to the event queue., – Lukas Knuth Jun 19 '15 at 15:25
  • The API for the requestFocus() method states: "developers are strongly encouraged to use `requestFocusInWindow()` when possible". – camickr Oct 12 '22 at 02:34
8

if is there only one Top-Level Container then last lines in GUI constructor would be for example

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

   @Override
     public void run() {
         myComponent.grabFocus();
         myComponent.requestFocus();//or inWindow
     }
});
mKorbel
  • 109,525
  • 20
  • 134
  • 319
6
public void actionPerformed(ActionEvent arg0)
{
    if (arg0.getSource()==clearButton)
    {
        enterText.setText(null);
        enterText.grabFocus();  //Places flashing cursor on text box        
    }       
}
kprice789
  • 61
  • 1
  • 1
2

Try this one,

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

   @Override
     public void run() {
         myComponent.grabFocus();
         myComponent.requestFocus();//or inWindow
     }
});
Dhanuka
  • 2,826
  • 5
  • 27
  • 38
Dulkith
  • 326
  • 3
  • 12
0

If the page contains multiple item and like to set the tab sequence and focus I will suggest to use FocusTraversalPolicy.

grabFocus() will not work if you are using FocusTraversalPolicy.

Sample code

int focusNumber = 0;
Component[] focusList;
focusList = new Component[] { game, move, amount, saveButton,
            printButton, editButton, deleteButton, newButton,
            settingsButton };

frame.setFocusTraversalPolicy(new FocusTraversalPolicy() {

        @Override
        public Component getLastComponent(Container aContainer) {
            return focusList[focusList.length - 1];
        }

        @Override
        public Component getFirstComponent(Container aContainer) {
            return focusList[0];
        }

        @Override
        public Component getDefaultComponent(Container aContainer) {
            return focusList[1];
        }

        @Override
        public Component getComponentAfter(Container focusCycleRoot,
                Component aComponent) {
            focusNumber = (focusNumber + 1) % focusList.length;
            if (focusList[focusNumber].isEnabled() == false) {
                getComponentAfter(focusCycleRoot, focusList[focusNumber]);
            }
            return focusList[focusNumber];
        }

        @Override
        public Component getComponentBefore(Container focusCycleRoot,
                Component aComponent) {
            focusNumber = (focusList.length + focusNumber - 1)
                    % focusList.length;
            if (focusList[focusNumber].isEnabled() == false) {
                getComponentBefore(focusCycleRoot, focusList[focusNumber]);
            }
            return focusList[focusNumber];
        }
    });
MukeshKoshyM
  • 514
  • 1
  • 8
  • 16
0

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.

Peter Quiring
  • 1,648
  • 1
  • 16
  • 21
0

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

It was not working for me when tried to use:

JOptionPane.showConfirmDialog(...)

But - I found a solution ! Very primitive, but works.

Just jump to the field by java.awt.Robot using key "Tab". For example:

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_TAB);
robot.delay(100);
robot.keyRelease(KeyEvent.VK_TAB);

If you should press multiple times on "Tab" to get your Component you can use below method:

GUIUtils.pressTab(3);

Definition:

public static void pressTab(int amountOfClickes)
{
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run()
        {
            try
            {
                Robot robot = new Robot();
                int i = amountOfClickes;
                while (i-- > 0)
                {
                    robot.keyPress(KeyEvent.VK_TAB);
                    robot.delay(100);
                    robot.keyRelease(KeyEvent.VK_TAB);
                }
            }
            catch (AWTException e)
            {
                System.out.println("Failed to use Robot, got exception: " + e.getMessage());
            }
        }
    });
}

If your Component location is dynamic, you can run over the while loop without limitation, but add some focus listener on the component, to stop the loop once arrived to it.

Adir Dayan
  • 1,308
  • 13
  • 21
0

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.

Ojonugwa Jude Ochalifu
  • 26,627
  • 26
  • 120
  • 132
0

How about put jTextField.requestFocusInWindow(); into jTextField FocusLost event? Works for me have 5 controls on JPanel Soon as click on MessageBox, focus lost on jTextField. Used all the suggested codes but no luck Only above method works my case.

Hana
  • 11
  • 3