I have developed a basic custom JTableModel as follows
public class CustomTableModel extends DefaultTableModel {
List<MyClass> data;
public CustomTableModel(List<MyClass> data) {
this.data = data;
}
public Class<?> getColumnClass(int columnIndex) {
return MyClass.class;
}
public MyClass getValueAt(int rowIndex, int columnIndex) {
return data.get(rowIndex);
}
// ...
}
I then use a basic custom JTableCellRenderer as follows
public class CustomTableCellRenderer extends JLabel implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
MyClass myClass = (MyClass)value;
lbl.setText(myClass.getString());
return this;
}
}
I also have a custom JPanel that displays various information as follows
public class MyPanel extends JPanel {
private MyClass myClass;
public MyPanel(MyClass myClass) {
// initialize components
}
public setMyClass(MyClass myClass) {
this.myClass = myClass;
updateFields();
}
private void updateFields() {
this.fieldString.setText(myClass == null ? "" : myClass.getString());
// ...
}
}
Finally, I use a table to list my data and the custom panel to display the details of the selected data.
public class JCustomFrame extends JFrame {
public JCustomFrame(List<MyClass> data) {
// ...
JTable table = new JTable(new CustomTableModel(data));
table.setDefaultRenderer(MyClass.class, new CustomTableCellRenderer());
}
}
What I am trying to accomplish is get the selected MyClass from the table regardless of sorting.
I tried ListSelectionListener but the methods do not return anything other than the selected indexes. Even if I have the index, if the table is sorted, my model is not so sophisticated and will return the wrong object.
...Even if I have the index, if the table is sorted, my model is not so sophisticated and will return the wrong object...
You have to use:
JTable.convertRowIndexToModel( int viewIndex )
Maps the index of the row in terms of the view to the underlying TableModel. If the contents of the model are not sorted the model and view indices are the same.
With that index you can access your table model and see what's the object you need.
Note Table sorting along with this method was introduced in Java 1.6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With