I have a Jtable that is populated with a linkedlist through an AbstractTableModel.
What I want to do is when I click (left-mouse click) on a row in the JTable, the linkedlist is search (in this case it contains movie titles) and displays the values in the linked list in Jtextboxes
How do I do this?
Here is the code
My guess it retrieve the data from the selected row into an array, split it, and put it into the jtextareas. How can I do this ?
Here's how I did it:
table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event) {
// do some actions here, for example
// print first column value from selected row
System.out.println(table.getValueAt(table.getSelectedRow(), 0).toString());
}
});
This code reacts on mouse click and item selection from keyboard.
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
JTable source = (JTable)evt.getSource();
int row = source.rowAtPoint( evt.getPoint() );
int column = source.columnAtPoint( evt.getPoint() );
String s=source.getModel().getValueAt(row, column)+"";
JOptionPane.showMessageDialog(null, s);
}
if you want click cell or row in jtable use this way
To learn what row was selected, add a ListSelectionListener
, as shown in How to Use Tables in the example SimpleTableSelectionDemo
. A JList
can be constructed directly from the linked list's toArray()
method, and you can add a suitable listener to it for details.
From the source with some enhancement and edit:
public class RowSelectionListener implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent event) {
int viewRow = table.getSelectedRow();
if (!event.getValueIsAdjusting() && viewRow != -1) {
int columnIndex = 1;
// Better to access table row using modelRow rather than viewRow
int modelRow = table.convertRowIndexToModel(viewRow);
// Access value at selected row at the second column (columnIndex = 1)
Object modelvalue = table.getModel().getValueAt(modelRow, columnIndex);
// Not recommended: same as above but access row using viewRow
Object tablevalue = table.getValueAt(viewRow, columnIndex);
// Print cell value
System.out.println(modelvalue + "=" + tablevalue);
}
}
}
Then add ListSelectionListener
to JTable
:
table.getSelectionModel().addListSelectionListener(new RowSelectionListener());
viewRow
and modelRow
become effectively different when applying TableRowSorter
.
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