且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java GUI:如何在JFrame上的JPanel中设置JButton的焦点?

更新时间:2023-12-05 09:13:58

试试这段代码..我所做的就是最后移动 requestFocus()方法。

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

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