简体   繁体   中英

Adding Extensions of JPanel to JFrame

I have a class that contains the main GUI window that my program will display

/**
 * GUI program to run a coffee/bagel shoppe
 * @author Nick Gilbert
 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class CoffeeShop extends JPanel {
    private final int WINDOW_WIDTH = 400;   // Window width
    private final int WINDOW_HEIGHT = 300;  // Window height
    private JFrame mainFrame;

    public CoffeeShop()
    {
        //Setting up mainframe configurations
        mainFrame = new JFrame();
        mainFrame.setTitle("Order Entry Screen!");
        mainFrame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setLayout(new BorderLayout());

        //Piecing together GUI window
        mainFrame.add(new TitleRegister(), BorderLayout.NORTH);
        mainFrame.setVisible(true);
    }

    public static void main(String[] args) {
        new CoffeeShop();
    }
}

As you can see, I'm trying to add to mainFrame a JPanel that is actually a class I wrote which extends JPanel

/**
 * Sets title at top of register
 * @author Nick Gilbert
 */
import javax.swing.*;

import java.awt.*;
import java.awt.Event.*;

public class TitleRegister extends JPanel {
    private JPanel titlePanel;
    private JLabel titleLabel;

    public TitleRegister() {
        titlePanel = new JPanel();
        titleLabel = new JLabel("Order Entry Screen", SwingConstants.CENTER);

        titlePanel.add(titleLabel);
        titlePanel.setVisible(true);
    }
}

Yet when I do this the instance of TitleRegister does not show up. I have setVisible set to true for everything so it should be showing up.

You've not actually added anything to the TitleRegister pane...

Without knowing more, you could simply getaway with...

public class TitleRegister extends JPanel {
    private JLabel titleLabel;

    public TitleRegister() {
        titleLabel = new JLabel("Order Entry Screen", SwingConstants.CENTER);

        add(titleLabel);
    }
}

In fact, you could simply get away with adding the JLabel to the mainFrame .

Notes:

There's no need to CoffeeShop to extend JPanel , you're not adding anything to, your constructor builds a JFrame and adds the UI to that...

Rely on pack over setSize , it will produce a more reliable output, ensuring that the content area has the space it needs to be properly displayed.

Make sure you are creating and modifying your UI's only from the context of the Event Dispatching Thread. See Initial Threads for more details...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM