我正在开发一个简单的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);
}
}
Current Look 如何使用java swing在前两列和最后两列之间添加一个isle?
答案 0 :(得分:3)
你可以使用两个面板(用于座位)和一个小岛,例如......
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
以产生差距... 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;
}