简体   繁体   English

JPanel和JFrame的大小是否相同?

[英]JPanel and JFrame same size, or not?

I'm trying to get JFrame and JPanel the same size, so I can align everything perfectly. 我试图让JFrameJPanel的大小相同,所以我可以完美地对齐所有内容。 But when I try this, the JPanel and JFrame appear to not be the same size. 但是当我尝试这个时, JPanelJFrame的大小似乎不一样。

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. 当我运行它时, contentPane大于frame What am I doing wrong? 我究竟做错了什么?

Instead of absolute position use LayoutManagers. 而不是绝对位置使用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. 在这种情况下,看起来像BorderLayout可用于安排您的GUI。 Always you remember you can layer different managers together to create more complicated effects. 总是你记得你可以将不同的经理分层,以创造更复杂的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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