简体   繁体   中英

Detecting Cell Click On A Table Row That Is Already Selected

I have a JFrame application that contains a JTabel . The underlying table model is my own class that I made that extends AbstractTableModel . The data in the first column is of type boolean and so I want it to show the value in the form of a checkbox. To do this, I added the following code in my table model getColumnClass method:

@Override
public Class<?> getColumnClass(int columnIndex) {
    if (columnIndex == 0) {
        return Boolean.class;
    } else if (columnIndex == 1) {
    ....
    ....
}

This works fine and my table cell looks like the following which is what I want:

JTable复选框列

The behavior I now want is that when the user clicks on a cell in column 0 of any row I want to toggle the value of On Sale .

My main class listens to selections in the table by implementing ListSelectionListener and overriding the valueChanged method. Inside the valueChanged method I can check the selected column by calling table.getSelectedColumn and checking to see if it's 0 then getting the object at the selected row and toggling the boolean on sale value.

The problem I am running into is that if a particular row is already selected and the user clicks the cell in column 0 for the selected row the valueChanged method is never called and so therefore I never toggle the value.

My quesion is, how do I detect a cell selection/click on a row that is already selected? Should I use a mouse selection listener then determine the cell that was clicked using the location data from the mouse click event?

Thank you.

Have you tried listening to table change instead ? You would need to implement TableModelListener and to have this :

 public void tableChanged(TableModelEvent e) {
    int row = e.getFirstRow();
    int column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    Object data = model.getValueAt(row, column);

    ...// Do something with the data...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM