开发者

Why does my JFrame stay empty, if I subclass JPanel and JFrame?

开发者 https://www.devze.com 2023-03-28 12:33 出处:网络
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:

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 = Settin开发者_如何学运维gs.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.


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

Why does my JFrame stay empty, if I subclass JPanel and JFrame?


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.


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


Why does my JFrame stay empty, if I subclass JPanel and JFrame?

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号