有如下代码:public class TestBorder extends JFrame{

public TestBorder()
{
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(9,9));
panel.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.blue));
JLabel label[] = new JLabel[81];
for(int i=0;i<label.length;i++)
{
label[i]=new JLabel(""+i);
label[i].setBorder(BorderFactory.createLineBorder(Color.red));
panel.add(label[i]);
}

this.add(panel);

this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setBounds(new Rectangle(245,345));
//this.setResizable(false);
this.setLocationRelativeTo(null);
this.setVisible(true);
}

public static void main(String args[])
{
new TestBorder();
}}为什么panel的最右边还会有一些空白的区域呢?
运行结果为:

解决方案 »

  1.   

    改变窗口的大小你会发现,边框的空白有时候会有,有时候没有,有时候小,有时候大,原因是像素是整数,而窗口的大小平均分成9分,不可能都是整数,还会有0-8个像素可能多出来,所以会出现上面的情况。
    要实现没有空白,必须得设置label的大小,然后frame使用pack函数去控制窗口的大小,或者自己手动计算窗口的大小
      

  2.   

    设置一下JLabel的preferredSize,然后 jframe pack。