What is the easiest way to display the contents of an ArrayList object in a JTable?

I have an ArrayList of Track object. Each Track object has the following fields (all lines):

url, title, creator, album, genre, composer

I want to display these tracks in JTable, with each row being an instance of the Track object and each column containing one of the properties of the Track object.

How can I display this data using JTable? I used AbstractTableModel, which implements the getValueAt () method correctly. However, I do not see anything on the screen.

Or is it easier to just use arrays?

+4
source share
2 answers

To add content to display on a JTable , use the TableModel to add items to display.

One way to add a data row to DefaultTableModel is with the addRow method, which will take an array from Object , which represents the objects in the row. Since there are no methods for directly adding content from an ArrayList , you can create an Object array by accessing the contents of an ArrayList .

The following example uses the KeyValuePair class, which is the data holder (similar to your Track class), which will be used to populate the DefaultTableModel to display the table as JTable :

 class KeyValuePair { public String key; public String value; public KeyValuePair(String k, String v) { key = k; value = v; } } // ArrayList containing the data to display in the table. ArrayList<KeyValuePair> list = new ArrayList<KeyValuePair>(); list.add(new KeyValuePair("Foo1", "Bar1")); list.add(new KeyValuePair("Foo2", "Bar2")); list.add(new KeyValuePair("Foo3", "Bar3")); // Instantiate JTable and DefaultTableModel, and set it as the // TableModel for the JTable. JTable table = new JTable(); DefaultTableModel model = new DefaultTableModel(); table.setModel(model); model.setColumnIdentifiers(new String[] {"Key", "Value"}); // Populate the JTable (TableModel) with data from ArrayList for (KeyValuePair p : list) { model.addRow(new String[] {p.key, p.value}); } 
+10
source

then the problem i am in is that i dont see the problem at all. here is the code i used to create the interface:

 public Interface(){ setSize(1024, 768); setBackground(new Color(0,0,0)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(new MenuBar());//simple JMenuBar implementation table= new JTable(); table.setPreferredScrollableViewportSize(new Dimension(500, 500)); JScrollPane jsp = new JScrollPane(table); add(jsp); pack(); setVisible(true); } 

after executing this code, I have code in another class that does this many times:

 ((DefaultTableModel)mainInterface.table.getModel()).addRow( new String[] {t.location,t.title,t.creator,t.album,t.genre,t.composer}); 

t is the track object, by the way.

0
source

All Articles