Reputation: 27
Im pretty new to Swing development in Java. I need some help with populating a table with some values that I have, after the initialization is done.
someClass extends JPanel{
private JLabel something;
static private JTable Table;
private JPanel temp;
someClass(){
setLayout(new BorderLayout());
selectSong = new JLabel("some text");
temp = new JPanel();
temp.setLayout(new FlowLayout());
temp.add(something);
Table = new JTable();
//Table.setVisible(false);
add(temp, BorderLayout.NORTH);
add(new JScrollPane(Table), BorderLayout.CENTER);
}
static void populateTable(ArrayList<String> list){
DefaultTableModel dtm = new DefaultTableModel();
dtm.addColumn("title", list.toArray());
Table = new JTable(dtm);
Table.setVisible(true);
new someClass().add(new JScrollPane(Table), BorderLayout.CENTER);
}
}
This class called someClass is a subclass of JPanel. I am using an object of this and appending it to the Main Frame(not shown here). According to this, initially a GUI form is created with an empty table, and after some operations are done, I call the populateTable function, I want this to change the values of the table to have one column (named title) and containing the arraylist elements in the subsequent rows.
Upvotes: 0
Views: 879
Reputation: 156
someClass extends JPanel{
private JLabel something;
static private JTable Table;
private JPanel temp;
private DefaultTableModel dtm;
someClass(){
setLayout(new BorderLayout());
selectSong = new JLabel("some text");
temp = new JPanel();
temp.setLayout(new FlowLayout());
temp.add(something);
dtm= new DefaultTableModel();
Table = new JTable(dtm);
add(temp, BorderLayout.NORTH);
add(new JScrollPane(Table), BorderLayout.CENTER);
}
static void populateTable(ArrayList<String> list){
dtm.addColumn("title", list.toArray());
}
}
this is how your class should look like
Upvotes: 1
Reputation: 1083
Assuming you called your JTable
'table':
static void populateTable(ArrayList<String> list){
DefaultTableModel dtm = new DefaultTableModel();
dtm.addColumn("title", list.toArray());
table.setModel(dtm);
}
}
You should also not call table.setVisible(true);
in that method, as it has nothing to do with populating the table.
Edit: as suggested by others: it would also be better to make use of a class attribute for the DefaultTableModel
.
Upvotes: 2