Java GridBagLayout在JFrame中不显示任何内容
我有一个使用GridBagLayout的JFrame。 我还向扩展JPanel的JFrame对象中添加了对象。当我使用GridLayout(1,2)时会显示面板,但我之所以需要GridBagLayout,是因为其中一个面板需要占用比另一个面板更多的空间Java GridBagLayout在JFrame中不显示任何内容,java,swing,jpanel,layout-manager,null-layout-manager,Java,Swing,Jpanel,Layout Manager,Null Layout Manager,我有一个使用GridBagLayout的JFrame。 我还向扩展JPanel的JFrame对象中添加了对象。当我使用GridLayout(1,2)时会显示面板,但我之所以需要GridBagLayout,是因为其中一个面板需要占用比另一个面板更多的空间 public class BoardFrame extends JFrame { private GridBagLayout gridLayout = new GridBagLayout(); private GridBagCo
public class BoardFrame extends JFrame
{
private GridBagLayout gridLayout = new GridBagLayout();
private GridBagConstraints constraints = new GridBagConstraints();
public BoardFrame()
{
super("Quoridor");
setLayout(gridLayout);
this.getContentPane().setBackground(Color.decode("#c6bf84"));
BoardPanel aBoardPanel = new BoardPanel(getHeight() , getWidth());
aBoardPanel.addMouseListener(aBoardPanel);
aBoardPanel.addMouseMotionListener(aBoardPanel );
TotalWallPanel wallPanel = new TotalWallPanel(aBoardPanel.getPlayers());
aBoardPanel.setwallPanelReference(wallPanel);
addComponent(aBoardPanel, 0, 0, 2, 1);
addComponent(wallPanel, 0, 1, 1, 1);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(1366, 768);
setVisible(true);
setResizable(false);
}
public void addComponent(Component component, int row , int col , int width , int height)
{
constraints.gridx = col;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
gridLayout.setConstraints(component, constraints);
this.add(component);
}
}
这段代码只显示了一个空帧。我不明白问题是在于我使用GridBagLayout的方式,还是在于相应面板的内部布局。两个面板的布局都设置为null,因为我使用绝对坐标在这些面板中绘制 注意BoardPanel aBoardPanel=新的BoardPanel(getHeight(),getWidth())代码>将与
BoardPanel aBoardPanel=新的BoardPanel(0,0)相同代码>在调用BoardPanel的构造函数之前,我使用了框架的setSize方法。我在最后发送它只是为了看看是否有任何更改setresizeable
会影响帧大小,因此最好在pack
之前调用它-因为问题的结果与要添加到视图中的组件有关,所以在任何人可能帮助您确定解决方案之前,您需要包含它们“两个面板的布局都设置为空,因为我使用绝对坐标在这些面板中绘制。”按照@MadProgrammer的建议发布一个MCVE,但我想指出这听起来很可疑。自定义绘制时,布局是不相关的(因此无需将其设置为null
)。任何时候,容器都应该有一个布局,即使它是您为该容器明确设计的布局。JVM使用布局管理器提供的提示来确定容器的适当大小。自定义绘制时,我们需要重写getPreferredSize()
方法以返回。。