3条回答 默认 最新
关注第一个问题,你的结果之所以不是3行3列, GridLayout(3,3)布局时,设定的列数只有在行数为0时才起作用;当行数不为0时,列数是由行数和添加的布局组件总数决定的。比如,你的程序里面,行数为3,布局组件总数为4,那么列数将被确定为2,所以,你会看到运行之后的布局。
第二个问题,你的p4有两行,所以就是这样的效果了。
修正代码如下(布局行数为0,p4为1行),可以看到你需要的效果:import java.awt.*; import javax.swing.*; public class JPanelTest extends JFrame{ public JPanelTest() throws HeadlessException { Container c = getContentPane(); c.setLayout(new GridLayout(0,3,10,10)); JPanel p1 = new JPanel(new GridLayout(1,1,10,10)); JPanel p2 = new JPanel(new GridLayout(1,2,10,10)); JPanel p3 = new JPanel(new GridLayout(1,2,10,10)); JPanel p4 = new JPanel(new GridLayout(1,1,10,10)); p1.add(new JButton("1")); p2.add(new JButton("2")); p3.add(new JButton("3")); p4.add(new JButton("4")); c.add(p1); c.add(p2); c.add(p3); c.add(p4); setSize(400,500); setVisible(true); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); } public static void main(String[] args) { new JPanelTest(); } }本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
