java JPanel类,空布局,不显示组件
因此,我创建了一个类“CustomPanel”的对象,它创建了一个JPanel,其中包含一个GridLayout和一个标签,然后我将它添加到我的JFrame中。显示标签“HELLO”效果很好,但是当我将jpanel的布局管理器更改为(null)时,它不会显示任何内容。我知道,我知道使用null布局是一种非常糟糕的做法,但我只想知道为什么它没有显示组件
主要类别:
import javax.swing.JFrame;
public class MainMenu extends javax.swing.JFrame{
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Size the window.
frame.setSize(500, 500);
CustomPanel panel = new CustomPanel();
frame.getContentPane().add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
带有GridLayout的CustomPanel类(这很好):
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CustomPanel extends JPanel{
public CustomPanel() {
initUI();
}
public final void initUI() {
// create the panel and set the layout
JPanel main = new JPanel();
main.setLayout(new GridLayout());
// create the labels
JLabel myLabel = new JLabel("HELLO");
// add componets to panel
main.add(myLabel);
this.add(main);
}
}
布局为空的CustomPanel类(这不起作用):
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CustomPanel extends JPanel{
public CustomPanel() {
initUI();
}
public final void initUI() {
// create the panel and set the layout
JPanel main = new JPanel();
main.setLayout(null);
// create the labels
JLabel myLabel = new JLabel("HELLO");
myLabel.setBounds(10, 10, myLabel.getPreferredSize().width, myLabel.getPreferredSize().height);
// add componets to panel
main.add(myLabel);
this.add(main);
}
}
jlabel在jpanel中设置正确,因此它应该显示在jframe的左上侧,但它没有。 这是什么原因造成的?我错过了什么
# 1 楼答案
问题是,如果没有使用适当的布局管理器,主JPanel的首选大小为0,0,并且不会显示在它所在的容器中。容纳主JPanel的CustomPanel使用FlowLayout,并将使用其包含的组件的首选大小来帮助确定这些组件的大小和位置,但由于main没有布局,将JLabel添加到main不会增加首选大小,因为这应该是使用布局的另一个原因,CustomPanel会将main显示为一个没有大小的点。当然,你可以通过
main.setPreferredSize(...)
给main一个首选大小来解决这个问题,但这样你就解决了一个不好的问题。另一个可能的解决方案是将CustomPanel的布局更改为其他可能会扩展其持有的主JPanel的布局,可能会给CustomPanel一个BorderLayout。在这种情况下,以默认方式将main添加到CustomPanel会将主JPanel放入BorderLayout。居中位置,将其展开以填充CustomPanel,很可能会看到JLabel当然,正确的解决方案是尽可能避免使用空布局