如果我对 JPanel 和 JFrame 进行子类化,为什么我的 JFrame 仍为空?

发布于 2024-11-29 11:25:42 字数 1687 浏览 1 评论 0原文

我正在尝试为我的 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

    }
}

但是当应用程序启动时,我看不到任何东西。只是一个大的灰色屏幕。

I'm trying to write custom JFrame and JPanel for my Java application. Currently, I just want to have a JPanel with a start button in the very middle of the screen. So, here's the code I have:

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

    }
}

and here is my panel:

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

    }
}

But when the application launches, I don't see anything. Just a big gray screen.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

只是偏爱你 2024-12-06 11:25:42

不要使用空布局。如果您只是使用 JPanel 的默认布局管理器(即 FlowLayout),则具有“自动”功能的 JButton 会被放置在中心。另外,为了将 JFrame 放置在屏幕中间,请调用 setLocationRelativeTo(null)


由于很难说出“屏幕”的含义,因此此示例展示了如何将 JFrame 中的 JPanel 中的 JButton 居中,即然后以监视器为中心。

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

在此处输入图像描述

Do not use a null layout. If you simply use the default layout manager of JPanel (i.e. FlowLayout), the JButton with "automagically" be placed in the center. Also, in order to place the JFrame in the middle of the screen, invoke setLocationRelativeTo(null).


Since it's hard to tell what you mean by "screen", this example shows how you center a JButton in a JPanel in a JFrame, that is then centered on the monitor.

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

始终不够爱げ你 2024-12-06 11:25:42

建议:

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

Recommendations:

  • Avoid using null layout as this makes your app difficult to upgrade and maintain and makes it potentially very ugly or even non-usable on boxes with different OS's or screen resolutions.
  • If you have your JPanel use a GridBagLayout and add a single component to it without using GridBagConstraints, it will be placed in the center of the JPanel.
  • You almost never have to or should extend JFrame and only infrequently need to extend JPanel. Usually it's better to enhance your GUI classes through composition rather than inheritance.
  • Avoid having your "view" or gui classes implement your listener interfaces. This is OK for "toy" programs, but as soon as your application gains any appreciable size or complexity, this gets hard to maintain.
┾廆蒐ゝ 2024-12-06 11:25:42

如果您不使用任何 LayoutManager (顺便说一句您可能应该使用),那么您需要 设置面板的大小(及其位置)。

尽管我们强烈建议您使用布局管理器,但您也可以在没有它们的情况下执行布局。通过将容器的布局属性设置为 null,可以使容器不使用布局管理器。使用这种称为绝对定位的策略,您必须指定该容器内每个组件的大小和位置。绝对定位的一个缺点是当顶层容器调整大小时它不能很好地调整。它也不能很好地适应用户和系统之间的差异,例如不同的字体大小和区域设置。

来自: http://download.oracle.com/javase/tutorial/uiswing /layout/using.html

If you don't use any LayoutManager (which btw you probably should), then you'll need to set the size of the panel as well (along with its position).

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.

From: http://download.oracle.com/javase/tutorial/uiswing/layout/using.html

凉城 2024-12-06 11:25:42

居中按钮

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

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());
            }
        });
    }
}
苍景流年 2024-12-06 11:25:42
addKeyListener(this); 

不要使用 KeyListener。 Swing 被设计为与键绑定一起使用。阅读 Swing 教程中有关如何使用键绑定的部分了解更多信息。

本教程还有一个关于使用布局管理器的部分,您应该阅读。您不应该创建具有空布局的 GUI。

addKeyListener(this); 

Don't use KeyListeners. Swing was designed to be used with Key Bindings. Read the section from the Swing tutorial on How to Use Key Bindings for more information.

The tutorial also has a section on Using Layout Manager which you should read. You should not create GUI's with a null layout.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文