chrisco
chrisco

Reputation: 832

Java GUI: How to Set Focus on JButton in JPanel on JFrame?

I've experimented and searched and I can't seem to figure out what I thought would be something simple, which is having my START button have focus when my little GUI app launches I.e., so all the user has to do is press their Enter/Return key, which will have the same effect as if they had clicked the START button with their mouse. Here is my code. Thanks for your help :)

private void initialize() {

   // Launch the frame:
   frame = new JFrame();
   frame.setTitle("Welcome!");
   frame.setSize(520, 480);
   frame.setLocationRelativeTo(null);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   // Add the image:
   ImageIcon heroShotImage = new ImageIcon("heroShot.jpg");
   JPanel heroShotPanel = new JPanel();
   JLabel heroShot = new JLabel(heroShotImage);
   heroShotPanel.add(heroShot);

   // Create a panel to hold the "Start" button:
   JPanel submitPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

   // Create the "Start" button, which launches business logic and dialogs:
   JButton start = new JButton("Start");
   start.setToolTipText("Click to use library");
   start.setFocusable(true); // How do I get focus on button on App launch?
   start.requestFocus(true); // Tried a few things and can't get it to work.

   // Listen for user actions and do some basic validation:
   start.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
      // THE APP's LOGIC GOES HERE...
      }

   // Finish setting up the GUI and its components, listeners, and actions:
   submitPanel.add(start);

   frame.getContentPane().add(heroShotPanel, BorderLayout.NORTH);
       frame.getContentPane().add(submitPanel, BorderLayout.SOUTH);

}

Upvotes: 21

Views: 65167

Answers (5)

mKorbel
mKorbel

Reputation: 109823

not easy job because Focus/Focus_SubSystem came from Native OS and is pretty asynchronous,

1) inside one Containers works by wraping that into invokeLater(),

2) manage Focus betweens two or more Top-Level Containers, by @camickr

Upvotes: 3

bragboy
bragboy

Reputation: 35572

Try out this code.. All I have done is moving the requestFocus() method at the end.

Basically these are the two things you have to do for it to respond while pressing enter key and for it to be focused by default.

frame.getRootPane().setDefaultButton(start);
start.requestFocus();

Screenshot of the image

package sof;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class TestFrame {

    public static void main(String[] args) {
        // Launch the frame:
        JFrame frame = new JFrame();
        frame.setTitle("Welcome!");
        frame.setSize(520, 480);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Add the image:
        ImageIcon heroShotImage = new ImageIcon("heroShot.jpg");
        JPanel heroShotPanel = new JPanel();
        JLabel heroShot = new JLabel(heroShotImage);
        heroShotPanel.add(heroShot);

        // Create a panel to hold the "Start" button:
        JPanel submitPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

        JButton start = new JButton("Start");
        start.setToolTipText("Click to use library");

        start.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("I AM PRESSED");
            }
        });

        submitPanel.add(start);

        frame.getContentPane().add(heroShotPanel, BorderLayout.NORTH);
        frame.getContentPane().add(submitPanel, BorderLayout.SOUTH);
        frame.setVisible(true);
        frame.getRootPane().setDefaultButton(start);
        start.requestFocus();
    }
}

Upvotes: 31

GETah
GETah

Reputation: 21459

If you want your start button to get the focus then do this at the end

//This button will have the initial focus.
start.requestFocusInWindow(); 

Upvotes: 3

Harry Joy
Harry Joy

Reputation: 59694

If I'm understanding you then you want to do a click event of Start Button when user hits Enter key. If this is the case then you can do it as follows:

jFrame.getRootPane().setDefaultButton(start);// 'start' will be your start button

And if you just want to get focus on start Button then shift your requestFocus() method at the end (after you make your frame visible) and no need to pass true in it. Also it is better to use requestFocusInWindow() then requestFocus() as stated in java doc.

Upvotes: 7

Adil Soomro
Adil Soomro

Reputation: 37729

move your focus line to the end of the method

and change it to

start.requestFocus();  // without params

Upvotes: 4

Related Questions