[英]Adding JPanel to JFrame?
I'm trying to add a JLabel to a JPanel to a JFrame. 我正在尝试将JLabel添加到JPanel到JFrame。 I set the border for the JPanel, but all I see on the JFrame is a small black square in the center of my frame. 我为JPanel设置了边框,但我在JFrame上看到的只是我框架中心的一个小黑方块。 Whatever I do I can't change the size or location of it. 无论我做什么,我都无法改变它的大小或位置。 Please help. 请帮忙。
Start main = new Start();
Random random = new Random();
JFrame mainFrame = new JFrame("MainFrame");
JPanel mainPanel = new JPanel();
JLabel welcomeLabel = new JLabel();
mainFrame.add(main);
mainFrame.setLayout(new GridBagLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setTitle(names[random.nextInt(names.length)]);
mainFrame.pack();
mainFrame.setVisible(true);
mainFrame.setSize(mainFrameX, mainFrameY);
mainFrame.setResizable(false);
mainFrame.setLocationRelativeTo(null);
mainFrame.add(mainPanel);
mainPanel.add(welcomeLabel);
mainPanel.setBorder(new LineBorder(Color.BLACK));
mainPanel.setSize(new Dimension(200, 200));
welcomeLabel.setFont(new Font("Verdana", 1, 20));
welcomeLabel.setLocation(100, 100);
main.start();
Suggestions: 建议:
Hovercraft is right (+1), make sure you understand how the layout managers are working. 气垫船是正确的(+1),确保你了解布局管理器是如何工作的。
The order in which you do things are important, especially when dealing with the top level containers... 您执行操作的顺序非常重要,尤其是在处理顶级容器时...
Start main = new Start();
Random random = new Random();
JFrame mainFrame = new JFrame("MainFrame");
JPanel mainPanel = new JPanel();
JLabel welcomeLabel = new JLabel();
welcomeLabel.setFont(new Font("Verdana", 1, 20));
mainPanel.add(welcomeLabel);
mainPanel.setBorder(new LineBorder(Color.BLACK));
// Do this first
mainFrame.setLayout(new GridBagLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setTitle(names[random.nextInt(names.length)]);
// Add your components
mainFrame.add(main);
mainFrame.add(mainPanel);
// Prepare the window for showing, now you have some content.
mainFrame.setResizable(false);
mainFrame.pack();
mainFrame.setVisible(true);
mainFrame.setLocationRelativeTo(null);
main.start();
This will still only produce a small black square in the window, because the JLabel
has no content and therefore it's preferred size is going to be (something like) 2x2 (because of the border). 这仍然只会在窗口中产生一个小的黑色方块,因为JLabel
没有内容,因此它的首选大小将是(类似于)2x2(因为边框)。
Try adding some text to... 尝试添加一些文字到......
welcomeLabel.setText("Welcome");
And then see the difference 然后看看差异
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.