Search code examples
javaswinguser-interfacejtablepropertychangelistener

Java swing UI implementation, most likely involving a PropertyChangeListener



My use case is as follows --
I have a list(ArrayList) of objects, custom data objects.
Now i want to display or represent each of these data objects as a Box containing 3 buttons. So i would have n Boxes for n given data objects in my list.

I want each of these 'boxes' to be stacked in a , say, JTable.

Now, whenever a data object is added to the aforementioned list, i want another Box to be created as mentioned before and added to the JTable.

I know this can be accomplished using PropertyChangeListener but i went through some articles online regarding PropertyChangeListener but was not able to get a clear implementable idea.

im new to building UIs and any help with this would be much appreciated.


Solution

  • 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);
      }
    }