I need to select a row when I click on the row on the JTable. The default behavior is when the mouse is pressed, the row gets selected. How can I change this behavior? My expectation is ::
mouse pressed --> mouse released ==> selected
mouse pressed --> mouse dragged -- > mouse released ==> not selected
mouse clicked ==> row selected
I want to do something else when mouse is dragged, but don't want to change the previous row selection on that action.
import java.awt.event.*;
import javax.swing.*;
/**
*
* @author Jigar
*/
public class JTableDemo extends MouseAdapter {
int selection;
public static void main(String[] args) throws Exception
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] headers = {"A", "B", "C"};
Object[][] data = {{1, 2, 3}, {4, 5, 6}};
JTable table = new JTable(data, headers);
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(table);
frame.add(scroll);
frame.pack();
frame.setVisible(true);
table.addMouseListener(new JTableDemo());
scroll.addMouseListener(new JTableDemo());
}
@Override
public void mousePressed(MouseEvent e)
{
JTable jtable = (JTable) e.getSource();
selection= jtable.getSelectedRow();
jtable.clearSelection();
}
@Override
public void mouseReleased(MouseEvent e){
JTable jtable = (JTable) e.getSource();
//now you need to select the row here check below link
}
}
I did not find this quite so easy. The table that I am trying to highlight rows in is not the currently active component, so you need something like:
// get the selection model
ListSelectionModel tableSelectionModel = table.getSelectionModel();
// set a selection interval (in this case the first row)
tableSelectionModel.setSelectionInterval(0, 0);
// update the selection model
table.setSelectionModel(tableSelectionModel);
// repaint the table
table.repaint();
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