我发布了一个简短的示例代码和2个屏幕截图。第一个没有在panels
内显示mainPanel
(frame
内部),我认为它们只是没有出现。
当我稍微扩展框架宽度时,面板显示出来,尽管面板的尺寸没有明确设置。 什么是背后的原因以及如何在我认真的申请中避免这种情况?
public class test extends JFrame {
public test() {
}
public static void main(String [] args){
JFrame frame= new JFrame();
Dimension size= frame.getPreferredSize();
size.width=200;
size.height=300;
frame.setPreferredSize(size);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.getContentPane().setLayout(new BorderLayout());
JPanel mainPanel= new JPanel();
mainPanel.setBorder(BorderFactory.createTitledBorder(
new EtchedBorder(), "Details", TitledBorder.CENTER,
TitledBorder.DEFAULT_POSITION, new Font("calibri", Font.PLAIN,
10)));
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
mainPanel.setLayout(new GridBagLayout());
JPanel panel1= new JPanel();
panel1.setBorder(BorderFactory.createTitledBorder(
new EtchedBorder(), "Panel1", TitledBorder.CENTER,
TitledBorder.DEFAULT_POSITION, new Font("calibri", Font.PLAIN,
10)));
//check...panel1.setBackground(Color.black);
GridBagConstraints c= new GridBagConstraints();
c.gridx= 0;
c.gridy=0;
c.weightx=1;
c.weighty=1;
c.fill= c.BOTH;
mainPanel.add(panel1, c);
JPanel panel2= new JPanel();
panel2.setBorder(BorderFactory.createTitledBorder(
new EtchedBorder(), "Panel2", TitledBorder.CENTER,
TitledBorder.DEFAULT_POSITION, new Font("calibri", Font.PLAIN,
10)));
//check..panel2.setBackground(Color.red);
c= new GridBagConstraints();
c.gridx=0;
c.gridy=1;
c.weightx=1;
c.weighty=2;
c.fill= c.BOTH;
mainPanel.add(panel2, c);
JPanel panel3= new JPanel();
panel3.setBorder(BorderFactory.createTitledBorder(
new EtchedBorder(), "Panel3", TitledBorder.CENTER,
TitledBorder.DEFAULT_POSITION, new Font("calibri", Font.PLAIN,
10)));
//check...panel3.setBackground(Color.blue);
c= new GridBagConstraints();
c.gridx=0;
c.gridy=2;
c.weightx=1;
c.weighty=6;
c.fill=c.BOTH;
mainPanel.add(panel3, c);
}
}
答案 0 :(得分:2)
frame.setVisible(true);
必须在将所有组件添加到框架及其子面板后执行上述声明。
当我稍微扩展框架宽度时,面板出现了,
调整框架大小时,会调用布局管理器,以便可以正确地设置和绘制组件。