简体   繁体   中英

JPanel and JFrame same size, or not?

I'm trying to get JFrame and JPanel the same size, so I can align everything perfectly. But when I try this, the JPanel and JFrame appear to not be the same size.

Here's my code:

public static void createWindow(){

    JPanel contentPane = new JPanel();
    contentPane.setSize(500,300);
    contentPane.setOpaque(true);
    contentPane.setBackground(Color.WHITE);
    contentPane.setLayout(null);

    JLabel welcomeLabel = new JLabel("Welcome to " + name,SwingConstants.CENTER);
    welcomeLabel.setSize(300,30);
    welcomeLabel.setLocation((contentPane.getWidth()/2)-(welcomeLabel.getWidth()/2),5); //Put the welcomeLabel in the uppercenter; does noet work.
    contentPane.add(welcomeLabel);

    JLabel versionLabel = new JLabel("TBRPG-Engine " + Main.getVersionNumber(), SwingConstants.CENTER);
    versionLabel.setSize(300,30);       
    versionLabel.setLocation(contentPane.getWidth()-versionLabel.getWidth(),contentPane.getHeight());   
    contentPane.add(versionLabel);      

    JFrame frame = new JFrame();
    frame.add(contentPane);
    frame.setTitle(name);
    frame.setSize(contentPane.getWidth(),contentPane.getHeight());
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

The contentPane is bigger than the frame when I run this. What am I doing wrong?

Instead of absolute position use LayoutManagers. Choose the correct one for your desired arrangement and it will not only simplify your code it will make it easier to update in the future.

In this case it looks like a BorderLayout could be used to arrange your GUI. Always you remember you can layer different managers together to create more complicated effects.

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