日期:2014-05-20  浏览次数:20872 次

新手请教设置JPanel之间距离问题
大家好。在一个JFrame上添加两个JPanel,想设置两个JPanel的距离,
FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 20, 20);
我想通过改变FlowLayout()的第二,三个参数改变,但不是起作用,下面是代码:
package ex;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Ex12_1 extends JFrame
{
public Ex12_1()
{
//试图通过这一行改变JPanel的距离,但不起作用。
FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 20, 20);
setLayout(flowLayout);

JPanel p1 = new JPanel();
p1.add(new JButton("Button1"));
p1.add(new JButton("Button2"));
p1.add(new JButton("Button3"));
add(p1, FlowLayout.LEFT);
//add(p1);

JPanel p2 = new JPanel();
p1.add(new JButton("Button4"));
p1.add(new JButton("Button5"));
p1.add(new JButton("Button6"));
add(p2, FlowLayout.LEFT);
//add(p2);

System.out.println(flowLayout.getHgap());
System.out.println(flowLayout.getVgap());

}
public static void main(String[] args)
{
// TODO Auto-generated method stub
Ex12_1 frame = new Ex12_1();
frame.setTitle("Exercise12_1");
frame.setSize(1000, 600);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}


------解决方案--------------------
两个这Panel放到一个Panel中 在把这个Panel设置边框就OK
------解决方案--------------------
添加 Box.createHorizontalStrut(int); 
or Box.createVerticalStrut(int);