gpt4 book ai didi

java - GridBagLayout:仅当我横向扩展 JFrame 时 JPanel 才会出现

转载 作者:行者123 更新时间:2023-12-02 05:51:46 24 4
gpt4 key购买 nike

我发布了一个简短的示例代码和 2 个屏幕截图。第一个没有显示 mainPanel 内的 panels (位于 frame 内),我认为它们只是没有显示。

当我稍微扩展框架宽度时,面板就会显示出来,尽管面板的尺寸尚未明确设置。 什么是其背后的原因以及如何在我的严肃应用程序中避免这种情况?

enter image description here

enter image description here

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);

}
}

最佳答案

frame.setVisible(true); 

上面的语句必须在所有组件添加到框架及其子面板之后执行。

When I expanded the frame width-wise just a little bit, the panels showed up,

当调整框架大小时,将调用布局管理器,以便可以正确定位和绘制组件。

关于java - GridBagLayout:仅当我横向扩展 JFrame 时 JPanel 才会出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23476355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com