JTable row selection

I need to select a row when I click on a row in JTable. The default behavior is when the mouse is pressed, a row is selected. How can I change this behavior? My expectation:

mouse clicked → mouse released ==> selected

mouse clicked → mouse dragged → mouse released ==> not selected

clicked ==> selected row

I want to do something else when the mouse is being dragged, but I do not want to change the previous row selection in this action.

+4
source share
3 answers
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 } } 
+6
source

I did not find it simple enough. The table I'm trying to highlight rows in is not 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(); 
+2
source

This is a "stange", but for me it worked:

 table.setDragEnabled(true); 
0
source

Source: https://habr.com/ru/post/1340286/


All Articles