Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTable row selection

Tags:

java

swing

jtable

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.

like image 677
george b Avatar asked Feb 25 '23 01:02

george b


2 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
    }



}
like image 70
jmj Avatar answered Mar 02 '23 00:03

jmj


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();
like image 24
Richard McMullin Avatar answered Mar 01 '23 23:03

Richard McMullin