2013-04-28 164 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