我创建了一个网格,扩展了 JPanel 覆盖图形,并且添加了一个 JPanel(GridBagLayout)并将 JPanel 添加到了 JFrame。但只有部分网格显示出来,其余部分全部隐藏在网格的右下角和左上角,接触 JPanel 的中间。
JFrame 的:setSize(500, 300);
JPanel 的:setSize(250, 250);
一直在尝试解决这个问题,但无法...请帮忙。
编辑:这是以下代码
public class Start extends JFrame{
public Start(){
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel(new GridBagLayout());
jp.add(grid);
add(jp, BorderLayout.CENTER);
setVisible(true);
}
}
//main method calling new Start();
public class DrawGrid extends JPanel{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
setSize(250, 250);
Graphics2D g2 = (Graphics2D) g;
//Grid algorithm here 20 x 20
}
最佳答案
永远不要从绘制方法中更改任何 UI 组件的状态,这可能会导致组件失效并引发一个或多个重绘请求,从而导致绘制请求无限循环,从而导致您的 PC内爆...好吧,至少它最终会消耗你的 CPU...
您的 DrawGrid
尚未定义供布局管理器使用的首选/最小/最大尺寸提示。
使用 setSize
不会执行任何操作,因为它将被布局管理器覆盖
相反,重写组件的 getPreferredSize
方法并向布局管理器返回“首选”尺寸
public class DrawGrid extends JPanel{
@Override
public Dimension getPreferredSize() {
return new Dimension(250, 250);
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
//Grid algorithm here 20 x 20
}
请注意,大小调整提示只是提示,布局管理器可以自行决定忽略其中一个或多个......
关于java - 为什么我的 Java GUI GridBagLayout 没有将 JPanel Grid 放在框架中间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26501487/