Question

I would like to create a table with the constructor method JTable(TableModel). What exact methods in the TableModel do I need to display the titles of each column?

Was it helpful?

Solution

You need to embed your JTable within a JScrollPane and the column headings will be shown automatically:

JScrollPane sp = new JScrollPane(new JTable());

OTHER TIPS

You need to implement a TableModel for example by extending the class AbstractTableModel or by to using a DefaultTableModel. This later has a constructor where you can set the number and names of your columns.

I think what you are really looking for the is the class DefaultTableModel. Just read through the documentation and you will be on your own way.

You need to implement the getColumnName method in the TableModel interface to return the column names you want.

From the Javadoc of TableModel:

String getColumnName(int columnIndex)
Returns the name of the column at columnIndex. This is used to initialize the table's column header name.

EDIT:
The abstract class AbstractTableModel provides implementation for most of the methods in interface TableModel and also provides a default implementation for the getColumnName method in interface TableModel (but which might not suit your purpose as it returns column names as A,B..).

Create your own TableModel by subclassing AbstractTableModel and provide implemenation for the abstract methods and override getColumnName method. For example you can try something like:

class MyTableModel extends AbstractTableModel {
   private List<String> rowData; // say 
   private List<String> columnNames; 

   MyTableModel(List<String> data,List<String> names) {
       rowData = data;
       columnNames = names;
   }

   // provide implementation of abstract methods
   public int getRowCount() {...}
   public int getColumnCount() {...} 
   public Object getValueAt(int row, int column) {...}

   @Override
   public String getColumnName(int pCol) {
       return columnNames.get(pCol);
   }
   ...
}

// create your table as below;
List<String> data = new ArrayList<String>();
data.add("Test");
data.add("Try");

List<String> colNames = new ArrayList<String>();
colNames.add("Name");

MyTableModel model = new MyTableModel(data,colNames);
JTable myTable = new JTable(model);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top