2015-10-20 125 views
3

我正在開發一個簡單的GUI,其中前兩列和後兩列JButton之間有一個島。代碼如下所示:JButton列之間的間距

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的前兩個和最後兩列之間的中間增加一個小島?

+0

使用兩個或兩個面板,每一個島;在一組按鈕之間添加一個空面板;使用'GridBagLayout'和插入< - 有三種不同的方法可以嘗試 – MadProgrammer

回答

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); 

Seats

使用「填充物「組件...

您可以在第2列和第3列之間放置」填充物「...

enter image description here

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; 
}