2013-04-28 199 views
0

我想要一個項目列表,當我按下+按鈕時,會添加一個新行。問題在於,儘管調用了用於添加項目的函數,但出於某種原因,面板從不更新。這是我的代碼:添加行不工作

public static GridBagConstraints getContraint() { 
     GridBagConstraints c = new GridBagConstraints(); 
     c.insets = new Insets(3, 3, 3, 3); 
     c.weightx = 1.0/3; 
     c.fill = GridBagConstraints.HORIZONTAL; 
     c.anchor = GridBagConstraints.CENTER; 
     c.gridy = 1; 
     return c; 
    } 
    public static void addRow(JPanel j, GridBagConstraints c) { 
     c.gridy++; 
     System.out.println("Test"); 
     for (int h = 0; h < 3; h++) { 
      c.gridx = h; 
      JTextField f = new JTextField(); 
      j.add(f, c); 
     } 
    } 
    public static JPanel createLayout(int rows) { 
     final JPanel product = new JPanel(new BorderLayout()); 
     final JPanel list = new JPanel(new GridBagLayout()); 
     String[] lables = {"School ", "Advanced #", "Novice # "}; 
     double weight = .3333333333333; 

     final GridBagConstraints c = getContraint(); 
     for (int j = 0; j < lables.length; j++) { 
      c.gridx = j; 
      JLabel f = new JLabel(lables[j]); 
      list.add(f, c); 
     } 

     for (int i = 0; i < rows; i++) { 
      addRow(list, c); 
     } 
//  c.gridy++; 
//  c.gridx = 0; 
//  c.gridwidth = GridBagConstraints.REMAINDER; 
//  c.anchor = GridBagConstraints.NORTHWEST; 
//  c.fill = GridBagConstraints.NONE; 

     JPanel b = new JPanel(); 
     JButton add = new JButton("+"); 
     add.addActionListener(new ActionListener() { 

      public void actionPerformed(ActionEvent e) { 
       addRow(list, c); 
       list.repaint(); 

      } 
     }); 
     b.add(add); 
     JButton delete = new JButton("-"); 
     b.add(delete); 
     product.add(b, BorderLayout.SOUTH); 
     product.add(list, BorderLayout.CENTER); 
     return product; 
    } 
    public static void printDebates(ArrayList<Judge> d) { 
     for (Judge j : d) { 
      System.out.printf("Judge: %s ", j.toString() + (j.getDebates().get(0).isAdvanced() ? 'A' : 'N')); 
      for (Debate de : j.getDebates()) { 
       System.out.printf("Round: %s ", de != null ? de.toString() : "null"); 
      } 
      System.out.print("\n"); 
     } 
    } 
    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); 
    } 

回答

4

JPanelj需求是revalidatedrepainted添加新的組件後:

j.revalidate(); 
j.repaint(); 

注意:添加行的功能已經被JTable組件

提供
+0

+1,JTable的建議是更好的設計。 – camickr 2013-04-29 00:06:57

+0

@camickr有趣的是,這是關於這個代碼的第三個問題,至少第三次'JTable'已被建議;) – MadProgrammer 2013-04-29 00:26:55

+0

@MadProgrammer,我沒有閱讀他關於該主題的第一個問題,也沒有想到關於JTable的第二個問題。但你是對的4個答案中有4個提出了一個表。希望OP會得到提示,而不是試圖重新發明輪子。 – camickr 2013-04-29 00:32:59