有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如果我是JPanel和JFrame的子类,为什么我的JFrame保持为空?

我正在尝试为我的Java应用程序编写自定义JFrame和JPanel。目前,我只想要一个在屏幕中间有一个开始按钮的JPanel。下面是我的代码:

package gui;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

@SuppressWarnings("serial")
public class SubitizingFrame extends JFrame implements KeyListener {

    public SubitizingFrame() {
        super("Subitizing");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addKeyListener(this);
        add(new LaunchPanel());

        pack();
        setVisible(true);
    }

    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_F5)
            System.out.println("F5 pressed");
    }

    public void keyReleased(KeyEvent e) {

    }

    public void keyTyped(KeyEvent e) {

    }
}

这是我的小组:

package gui;

import instructions.Settings;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class LaunchPanel extends JPanel implements ActionListener {

    private JButton startButton;

    public LaunchPanel() {
        int width = Settings.getScreenSizeX(), height = Settings.getScreenSizeY();
        setPreferredSize(new Dimension(width, height));
        setLayout(null);
        startButton = new JButton("Start");
        startButton.setLocation((width/2) - (startButton.getWidth()/2), (height/2) - (startButton.getHeight()/2));
        add(startButton);
    }

    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub

    }
}

但是当应用程序启动时,我什么也看不到。只是一个灰色的大屏幕


共 (5) 个答案

  1. # 1 楼答案

    如果您不使用任何LayoutManager(顺便说一句,您可能应该使用),那么您也需要使用面板的set the size(以及它的位置)

    Although we strongly recommend that you use layout managers, you can perform layout without them. By setting a container's layout property to null, you make the container use no layout manager. With this strategy, called absolute positioning, you must specify the size and position of every component within that container. One drawback of absolute positioning is that it does not adjust well when the top-level container is resized. It also does not adjust well to differences between users and systems, such as different font sizes and locales.

    发件人:http://download.oracle.com/javase/tutorial/uiswing/layout/using.html

  2. # 2 楼答案

    addKeyListener(this); 
    

    不要使用键盘监听器。Swing设计用于键绑定。阅读Swing教程中关于How to Use Key Bindings的部分以了解更多信息

    本教程还有一个关于Using Layout Manager的部分,您应该阅读。您不应该创建带有空布局的GUI

  3. # 3 楼答案

    不要使用空布局。如果只使用默认布局管理器JPanel(即FlowLayout),则带有“自动”的JButton将被放置在中间。此外,为了将^ {< CD4}}放置在屏幕的中间,调用^{}


    由于很难说出“屏幕”是什么意思,本例显示了如何将JButton集中在JPanel集中在JFrame中,然后集中在显示器上

    public final class CenterComponentsDemo {
    
        public static void main(String[] args){
            SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run() {
                    createAndShowGUI();                 
                }
            });
        }
    
        private static void createAndShowGUI(){
            final JFrame frame = new JFrame("Center Components Demo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new ButtonPane());
            frame.setSize(new Dimension(300, 100)); // Done for demo
            //frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        private static class ButtonPane extends JPanel{
            public ButtonPane(){
                super();
                setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                setBackground(Color.PINK);
                final JButton button = new JButton("Start");
                button.setAlignmentX(Component.CENTER_ALIGNMENT);
                add(Box.createVerticalGlue());
                add(button);
                add(Box.createVerticalGlue());
            }
        }
    }
    

    enter image description here

  4. # 4 楼答案

    Centered Button

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    
    public class LaunchPanel extends JPanel {
    
        private JButton startButton;
    
        public LaunchPanel() {
            int width = 200, height = 100;
            setPreferredSize(new Dimension(width, height));
            setLayout(new GridBagLayout());
            startButton = new JButton("Start");
            add(startButton);
            setBorder( new LineBorder(Color.RED, 2));
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JOptionPane.showMessageDialog(null, new LaunchPanel());
                }
            });
        }
    }
    
  5. # 5 楼答案

    建议:

    • 避免使用空布局,因为这会使你的应用程序难以升级和维护,并且可能会非常难看,甚至无法在不同操作系统或屏幕分辨率的设备上使用
    • 如果您让您的JPanel使用GridBagLayout并在不使用GridBagConstraints的情况下向其添加单个组件,它将被放置在JPanel的中心
    • 您几乎不需要或应该扩展JFrame,只需要偶尔扩展JPanel。通常,最好通过组合而不是继承来增强GUI类
    • 避免让“视图”或gui类实现侦听器接口。这对于“玩具”程序来说是可以的,但一旦应用程序的大小或复杂度增加,就很难维护