我正在尝试列出一些项目,当我点击+
按钮时,会添加一个新行。问题是虽然调用了用于添加项目的函数,但由于某种原因,面板永远不会更新。这是我的代码:
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);
}
答案 0 :(得分:4)
添加新组件后,JPanel
j
必须为revalidated
和repainted
:
j.revalidate();
j.repaint();
注意:JTable
组件