且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在我将组件添加到JFrame而不是将它们添加到JPanel之后,所有这些组件都消失了?

更新时间:2022-02-17 01:37:26

这是因为默认情况下,JPanel使用

This is because by default a JPanel uses a FlowLayout that shows added Components one after the other

JFrame使用 BorderLayout 最多可以放置五个组件(每个区域PAGE_START,PAGE_END,LINE_START,LINE_END和CENTER中的一个).如果未指定区域,则组件将放置在CENTER区域中.如果您尝试在一个区域中放置一个以上的组件,则会显示最后一个.

JFrame uses a BorderLayout where at most five components can be placed (one in each of the regions PAGE_START, PAGE_END, LINE_START, LINE_END, CENTER). If you don't specify the region the component is placed into the CENTER region. If you try to place more than one component into one region one the last one will show up.

对于您的问题,我建议创建一个包含您的JLabelJComboBoxJRadioButtonJButtonJPanel,并像这样将JPanel添加到JFrame:>

For your problem I would recommend to create a JPanel that contains your JLabel, JComboBox, JRadioButton and the JButton and add the JPanel to the JFrame like this:

JPanel buttonPanel = new JPanel();
buttonPanel.add(label1);  // instead of jf.add(label1);
buttonPanel.add(cmbox);   // instead of jf.add(cmbox);
buttonPanel.add(rb2);     // instead of jf.add(rb2);
buttonPanel.add(btPlay);  // instead of jf.add(btPlay);
jf.add(buttonPanel, BorderLayout.PAGE_START);


为什么不显示组件


Why your components don't show up if you do

jf.setLayout(null); 
jp1.setBounds(0, 100, 1368, 730);

这很简单:如果要通过编写jf.setLayout(null);来使用绝对定位,则必须自己定义每个组件的边界.

That is simple: if you want to use absolute positioning by writing jf.setLayout(null); you have to define the bounds of every component yourself.

这并不能很好地扩展:这是一个繁琐的任务,如果人们使用不同的字体大小设置,几乎可以保证会让某人不满意.

And that doesn't scale well: it is a tedious task and if people have different font size settings you are almost guaranteed to make somebody unhappy.

***学习各种布局管理器的工作方式并适当地使用它们.要了解布局管理器,您可以在 https://docs中找到重要的文档. .oracle.com/javase/tutorial/uiswing/layout/index.html

It is much better to learn how the various layout managers work and use these appropriately. To learn about the layout managers you find important documentation at https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html