Java GUI: как настроить фокус на JButton в JPanel на JFrame?

Я экспериментировал и искал, и я не могу понять, что, по моему мнению, будет чем-то простым, у меня есть кнопка "СТАРТ" с фокусом, когда мое маленькое приложение GUI запускает Ie, поэтому все, что нужно сделать пользователю нажмите клавишу Enter/Return, которая будет иметь такой же эффект, как если бы они нажали кнопку START с помощью мыши. Вот мой код. Спасибо за помощь:)

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 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);

}

Ответы

Ответ 1

Попробуйте этот код. Все, что я сделал, это перемещение метода requestFocus() в конце.

В основном, это две вещи, которые вы должны выполнить для ответа, нажав клавишу ввода, и чтобы она была сфокусирована по умолчанию.

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();
    }
}

Ответ 2

Если я понимаю вас, вы хотите сделать событие щелчка кнопки "Пуск", когда пользователь нажимает клавишу Enter. Если это так, вы можете сделать это следующим образом:

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

И если вы просто хотите сосредоточиться на кнопке Start, тогда смените свой метод requestFocus() в конце (после того, как вы сделаете свой кадр видимым), и вам не нужно передавать true в нем. Также лучше использовать requestFocusInWindow(), затем requestFocus(), как указано в java doc.

Ответ 3

Если вы хотите, чтобы ваша кнопка start получала фокус, сделайте это в конце

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

Ответ 4

переместите линию фокусировки в конец метода

и измените его на

start.requestFocus();  // without params