Reputation: 79
I have a LinkedHashSet
of Book
objects. The Book
objects have the following fields:
private int id;
private String author = "";
private String title = "";
private boolean isRead;
private String dateStamp = "";
private static int counter = 0;
I want them to go into my JTable
which has the following columns:
String [] columnNames = {"ID","Title", "Author", "Status", "Date Read"};
How can I do this? And is it possible to have the isRead
field being editable through a checkbox in the table?
Upvotes: 0
Views: 1001
Reputation: 205805
As a concrete example of using AbstractTableModel
, you can leverage the toArray()
method inherited by LinkedHashSet
to simplify the implementation of getValueAt()
, as shown in this related EnvTableTest
. The default JTable
renderer and editor use JCheckBox
for TableModel
elements of type Boolean.class
, as shown in this example.
Upvotes: 1
Reputation: 8865
This is a sample model I have created for the table.
public class CustomModel extends AbstractTableModel {
private Object[] colNames ={"ID","Title", "Author", "Status", "Date Read"};
private LinkedHashSet<CustomClass> data;
public TableModelTop() {
this.data = getDataForDropList();
}
public int getRowCount() {
return data.size();
}
public int getColumnCount() {
return colNames.length;
}
@Override
public String getColumnName(int columnIndex) {
return (String) colNames[columnIndex];
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
// Set Values here;
}
public Object getValueAt(int rowIndex, int columnIndex) {
// Get row Values here;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
// Depending on the type of the column. Return data type;
}
/**
* Populate the data from here.
* @return LinkedHashSet<CustomClass>
*/
private LinkedHashSet<CustomClass> getDataForDropList() {
LinkedHashSet<CustomClass> modelList = new LinkedHashSet<CustomClass>();
for(int i = 0; i< 5; i++) {
// Create custom Object and add them to the LinkedHashSet.
// Create a CustomClass object and add it to the LinkedHashSet
modelList.add(customClassObject);
}
// Finally return the llinkedhashset
return modelList;
}
}
After this just call the table model and assign this to the JTable.
JTable table = new JTable(new CustomModel());
Upvotes: 1
Reputation: 8205
You need to have a class that extends AbstractTableModel
. This class should use your LinkedHashSet
as the data source for your table. The basic implementation provided by AbstractTableModel
should suit most of your needs. If not, then you can override the methods you need to customize.
This tutorial should help you understand how JTable
objects work.
Upvotes: 1