最近写了个迷宫游戏,应经完成了,可地图铺不满框架!不美观!后来又写了个小程序试了试问题还在,大家看看吧
这个例子就能看出为题:
import java.awt.*;
import javax.swing.*;public class Ex extends JFrame
{
JPanel panel;
JButton[] cells;
public Ex()
{
this.setSize(600,600);
this.setLocation(240,100);

addPanel();

this.setVisible(true);
this.setDefaultCloseOperation(3);
}
public void addPanel()
{
panel=new JPanel();
panel.setLayout(new GridLayout(30,30));
cells=new JButton[900];
for(int i=0;i<900;i++)
{
cells[i]=new JButton(i+"");
panel.add(cells[i]);
}
this.add(panel);
}

public static void main(String[] args)
{
new Ex();
}
}而且是按钮越多越是铺不满,可以把它拉大拉小试试看,谁能解释下为啥?怎么解决???
求大侠们帮帮忙!

解决方案 »

  1.   

    在方法里面加一句
    this.pack();
    一般在this.setVisible(true)附近。
      

  2.   

    做Swing一般是这样的:
    由于JFrame里有个ContentPane,所以其他的东西都在JPanel上设置好之后,把JPanel设置为JFrame的ContentPane,这样就好了。import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;public class Main extends JFrame { public Main() {
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setContentPane(new MyPanel());
    this.pack();
    this.setVisible(true);

    }

    public static void main(String[] args) {
    new Main();
    } class MyPanel extends JPanel {
    public MyPanel() {
    this.setPreferredSize(new Dimension(600, 600));
    this.setLayout(new GridLayout(30, 30));
    JButton[] cells;
    cells = new JButton[900];
    for (int i = 0; i < 900; i++) {
    cells[i] = new JButton(i + "");
    this.add(cells[i]);
    }
    }
    }

    }
      

  3.   

    楼主你对你的panel用一下
    setBackground(Color.RED);
    你会发现背景变红了
    这说明一个问题
    并不是这个panel没有填满你的JFrame
    而是GridLayout布局没有让所有的Button填满这个panel
      

  4.   

    楼主你对你的panel用一下
    setBackground(Color.RED);
    你会发现背景变红了
    这说明一个问题
    并不是这个panel没有填满你的JFrame
    而是GridLayout布局没有让所有的Button填满这个panel
      

  5.   

    设置为CENTER 再调用pack() 呢?
      

  6.   

     哈哈,我找到问题了,是Panel的宽高不能被Button数组的列行整除造成的,Frame的宽高是比Panel的大了一点,让Frame跟着Panel的大小而变,设定Panel的宽高,让其能整除Button数组的列行即可解决问题!三楼的做法就是这样,很不错!谢谢各位大侠帮忙!