JButton列之间的间距

我正在开发一个简单的GUI,其中前两列和JButtons的下两列之间有一个小岛。 代码如下:

JPanel panel = new JPanel(new GridLayout(50, 4)); JScrollPane scrollable = new JScrollPane(panel); for (int row = 0; row < rows; row++) { for (int column = 0; column < columns; column++) { JButton button = new JButton("Row " + row + " seat " + column); panel.add(button); } } 

当前外观如何使用java swing在前两列和后两列之间添加一个isle?

使用两个面板……

您可以使用两个面板(用于座椅)和一个岛,例如……

 JPanel left = new JPanel(new GridLayout(0, 2)); JPanel isle = new JPanel(); JPanel right = new JPanel(new GridLayout(0, 2)); for (int row = 0; row < 10; row++) { for (int col = 0; col < 4; col++) { JButton btn = new JButton("Row " + row + " seat " + col); if (col < 2) { left.add(btn); } else { right.add(btn); } } } setLayout(new GridLayout(1, 3)); add(left); add(isle); add(right); 

座位

使用“填充物”组件......

你可以在第2列和第3列之间放置一个“填充”组件......

在此处输入图像描述

 setLayout(new GridLayout(0, 5)); for (int row = 0; row < 10; row++) { for (int col = 0; col < 4; col++) { JButton btn = new JButton("Row " + row + " seat " + col); if (col == 2) { add(new JPanel()); } add(btn); } } 

使用GridBagLayout并应用insets来产生差距......

GridBagLayout的

 setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; for (int row = 0; row < 10; row++) { gbc.insets = new Insets(1, 1, 1, 1); for (int col = 0; col < 4; col++) { JButton btn = new JButton("Row " + row + " seat " + col); if (col == 2) { gbc.insets = new Insets(1, 40, 1, 1); } else { gbc.insets = new Insets(1, 1, 1, 1); } add(btn, gbc); gbc.gridx++; } gbc.gridy++; gbc.gridx = 0; }