1


我的用例如下——
我有一个对象列表(ArrayList),自定义数据对象。
现在我想将这些数据对象中的每一个显示或表示为一个包含 3 个按钮的框。所以我会有n盒子n在我的列表中有给定数据对象的

我希望这些“盒子”中的每一个都堆叠在JTable.

现在,每当将数据对象添加到上述列表中时,我都希望像前面提到的那样创建另一个 Box 并将其添加到 JTable 中。

我知道这可以使用 PropertyChangeListener 来完成,但我在网上浏览了一些关于 PropertyChangeListener 的文章,但无法得到一个明确的可实施的想法。

我是构建 UI 的新手,对此的任何帮助将不胜感激。

4

1 回答 1

2

I would recommend wrapping your ArrayList within a TableModel implementation, whereby modifications to the list will fire a TableModelEvent.

In the example below the underlying List is encapsulated within the model implementation; the only way to modify it is by calling addItem, which will call fireTableRowsInserted after modifying the list. This will result in a TableModelEvent being fired and subsequently processed by the JTable view onto this model instance.

public class MyTableModel extends AbstractTableModel {
  private final List<MyItem> items = new ArrayList<MyItem>();

  public int getRowCount() {
    return items.size();
  }

  public int getColumnCount() {
    return 3;
  }

  public String getColumnName(int columnIndex) {
    switch(columnIndex) {
      case 0:
        return "foo";
      case 1:
        return "bar";
      case 2:
        return "qux";
      default:
        assert false : "Invalid column index: " + columnIndex;
    }
  }

  public void addItem(MyItem item) {
    items.add(item);
    fireTableRowsInserted(items.size() - 1, items.size() - 1);
  }
}
于 2012-03-15T15:20:34.180 回答