Just to illustrate, the following are examples of how to use the DefaultTableModel
to show your data from HashMap
s and Vector
s.
The following is an example of dumping data from a HashMap
onto a DefaultTableModel
which is used as the TableModel
of a JTable
.
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class JTableExample extends JFrame
{
private void makeGUI()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// HashMap with some data.
HashMap<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
// Create a DefaultTableModel, which will be used as the
// model for the JTable.
DefaultTableModel model = new DefaultTableModel();
// Populate the model with data from HashMap.
model.setColumnIdentifiers(new String[] {"key", "value"});
for (String key : map.keySet())
model.addRow(new Object[] {key, map.get(key)});
// Make a JTable, using the DefaultTableModel we just made
// as its model.
JTable table = new JTable(model);
this.getContentPane().add(table);
this.setSize(200,200);
this.setLocation(200,200);
this.validate();
this.setVisible(true);
}
public static void main(String[] args)
{
new JTableExample().makeGUI();
}
}
For using a Vector
to include a column of data into a JTable
:
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class JTableExample extends JFrame
{
private void makeGUI()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Vector with data.
Vector<String> v = new Vector<String>();
v.add("first");
v.add("second");
// Create a DefaultTableModel, which will be used as the
// model for the JTable.
DefaultTableModel model = new DefaultTableModel();
// Add a column of data from Vector into the model.
model.addColumn("data", v);
// Make a JTable, using the DefaultTableModel we just made
// as its model.
JTable table = new JTable(model);
this.getContentPane().add(table);
this.setSize(200,200);
this.setLocation(200,200);
this.validate();
this.setVisible(true);
}
public static void main(String[] args)
{
new JTableExample().makeGUI();
}
}
I have to admit that the column names don't appear when using the above examples (I usually use the DefaultTableModel
's setDataVector
method), so if anyone has any suggestions on how to make the column names appear, please do :)