2012-09-12 24 views
1

我目前有一个JButtons数组,我想将它们放在两列中的JPanel上,均匀分割​​。所以如果数组中有8个按钮,左列将会有4个按钮,右列将会有4个按钮。但是,如果数组中有7个按钮,则左列将包含4个按钮,右列将包含3个按钮。如何在两列之间动态添加动态分配的组件?

我开始研究并为这种情况创建了一些基本逻辑,并想知道我所做的代码是否存在逻辑错误(或者可能是更好的方法)。

这里是代码,我拿出

public class SwingTest { 

    public static void main(String[] args) { 
     JFrame frame = new JFrame(); 

     JButton b1 = new JButton(); 
     b1.setText("Button1"); 

     JButton b2 = new JButton(); 
     b2.setText("Button2"); 

     JButton b3 = new JButton(); 
     b3.setText("Button3"); 

     JButton b4 = new JButton(); 
     b4.setText("Button4"); 

     JButton b5 = new JButton(); 
     b5.setText("Button5"); 

     JButton b6 = new JButton(); 
     b6.setText("Button6"); 

     ArrayList<JButton> jButtonList = new ArrayList(); 
     jButtonList.add(b1); 
     jButtonList.add(b2); 
     jButtonList.add(b3); 
     jButtonList.add(b4); 
     jButtonList.add(b5); 
     jButtonList.add(b6); 

     JPanel panel = new JPanel(); 
     panel.setLayout(new java.awt.GridBagLayout()); 

     double halfList = Math.ceil((jButtonList.size()/2.0)); 
     int gridX = 0, gridY = 0; 

     for(int i = 0; i < jButtonList.size(); i++) { 
      GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints(); 

      if(gridY == (int)halfList) { 
       gridX++; 
       gridY = 0; 
      } 
      gridBagConstraints.gridx = gridX; 
      gridBagConstraints.gridy = gridY; 
      gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; 
      gridBagConstraints.weightx = 1.0; 
      gridBagConstraints.weighty = 1.0; 
      gridBagConstraints.insets = new java.awt.Insets(1, 0, 1, 0); 
      panel.add(jButtonList.get(i), gridBagConstraints); 
      gridY++; 
     } 
     frame.add(panel); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
} 

的示例代码看起来做工精细,但还能有它可能打嗝的情况下?

回答

4

您可以使用一个JPanel与GridLayout的传递零线在其构造与2列:

JPanel panel = new JPanel(new GridLayout(0 ,2)); 

这意味着该小组将在高度上增加当您添加组件,同时仍然保持始终为2列

添加这些Jbutton将是如此简单的代码:

for(int i = 0; i < jButtonList.size(); i++) { 
    panel.add(jButtonList.get(i)); 
} 
+0

我会尽快尝试,因为它比我当前的代码少得多。 - 测试过!这段代码确实做得很好。感谢您的信息。在将此标记为最佳答案之前,我现在在那里的逻辑有什么问题吗? – WilliamShatner

+0

我对此不确定的一件事是,它按行添加按钮而不是按列添加按钮(还没有决定是否希望它们按行或列添加) – WilliamShatner

+0

您的逻辑可以,只需更改FOR对于我放在这里的panel.setLayout和panel.setLayout(新的GridLayout(0,2)应该可以工作 – Roger

1

使用此一GridBagLayout似乎是一个很好的计划。

但是,我会清理一下按钮构建代码。如果你需要100个按钮会发生什么?手动添加100个按钮似乎不是一个好主意。我将有一个参数化方法来构建和返回一个按钮和一个循环,用于将按钮添加到您的ArrayList

+0

以上只是一个SSCCE,所以其他人可以快速构建代码,并且可能会发现上面的逻辑不会不工作,我主要想知道我的逻辑是否正确地分割列 – WilliamShatner