2013-04-28 30 views
2

我有添加行到GridBagLayout的代碼,但我無法弄清楚如何刪除它。當某個按鈕被點擊時,我想擺脫佈局的最後一行。如何刪除GridBagLayout的行

這是增加了它們的代碼:

public static JPanel createLayout(int rows) { 
    JPanel product = new JPanel(new GridBagLayout()); 
    String[] lables = {"School ", "Advanced #", "Novice # "}; 
    double weight = .3333333333333; 

    GridBagConstraints c = new GridBagConstraints(); 
    c.insets = new Insets(3, 3, 3, 3); 
    c.weightx = weight; 
    c.fill = GridBagConstraints.HORIZONTAL; 
    c.anchor = GridBagConstraints.CENTER; 
    c.gridy = 1; 
    for (int j = 0; j < lables.length; j++) { 
     c.gridx = j; 
     JLabel l = new JLabel(lables[j]); 
     product.add(l, c); 
    } 

    for (int i = 0; i < rows; i++) { 
     c.gridy++; 
     for (int j = 0; j < lables.length; j++) { 
      c.gridx = j; 
      JTextField f = new JTextField(); 
      product.add(f, c); 
     } 
    } 
    c.gridy++; 
    c.gridx = 0; 
    c.anchor = GridBagConstraints.NORTHWEST; 
    c.fill = GridBagConstraints.NONE; 

    JPanel b = new JPanel(); 
    JButton add = new JButton("+"); 
    b.add(add); 
    JButton delete = new JButton("-"); 
    b.add(delete); 
    product.add(b, c); 
    return product; 
} 
public static void main(String[] args) throws IOException { 
    JFrame frame = new JFrame("Debate Calculator"); 
    JPanel debates = new JPanel(); 
    frame.add(createLayout(5), BorderLayout.NORTH); 
    frame.pack(); 
    frame.setVisible(true); 
} 

那麼,如何刪除行?

+3

使用['JTable'(http://docs.oracle.com/javase/tutorial/uiswing/components/table.html),這是它的設計爲 – MadProgrammer 2013-04-28 23:33:30

回答

2

如果你堅持自己做這一切,你將需要維護某種模型,所以你知道一切都在哪裏。

首先將各行組件添加到某種List。當你刪除一行時,你可以簡單地找到組成該行的所有組件,並將它們從容器中移除。

這會向您提出問題。因爲最後一行的y位置可能與行數相匹配。 (即,您不能簡單地執行c.gridy = listOfComponents.size()來確定添加下一行的位置)。

GridBagConstraints但是,您可以獲取用於佈局給定組件的約束條件。這意味着您可以找到list中的最後一行,獲得第一列的約束條件,並且您將能夠推斷出最後一個y的位置......有關詳細信息,請參閱GridBagConstraints#getConstraints

或者你可以只使用一個JTable

+0

+1建議使用一個JTable,一次又一次.... – camickr 2013-04-29 00:35:22

+0

感謝更復雜的答案JTable無法滿足複雜的要求的情況下! – Daniel 2017-01-11 20:26:23