java: how to select only one cell in a jtable and not the whole row

老子叫甜甜 提交于 2020-12-30 07:31:18

问题


in a jTable, I want when a user clicks on a cell, this sentence to be printed on the screen :

I am cell in row X and column Y

where x and Y are the row and column of the clicked cell. But what I am getting is : when I click for example the cell in row 1 and column 4 I get the following :

I am cell in row 1 and column 0
I am cell in row 1 and column 1
I am cell in row 1 and column 2
....
I am cell in row 1 and column N  ( N = number of columns)

i.e. the whole row is selected.

this is the code :

public class CustomTableCellRenderer extends DefaultTableCellRenderer{

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{

    Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            if(isSelected) System.out.println("I am cell in row "+row+" and column "+column);



    return cell;

}

}

Thanks for any help.


回答1:


CellRenderers are used for rendering the cell contents. If you want to find the cell in which the mouse clicked, use a MouseListener and in the mouseClicked method find the cell.




回答2:


You shouldn't use a cell renderer for this.

Enable cell selection on your table (using setCellSelectionEnabled(true)), then get the selection model of the table (using getSelectionModel()), and add a listener on this selection model. Each time an event is triggered, use getSelectedRow() and getSelectedColumn() to know which cell is selected.

Note that this will give you the selected cell, which can be modified using the mouse or the keyboard. If you just want to know where the mouse clicked, then see KDM's answer.




回答3:


myTable.setRowSelectionAllowed(false);



回答4:


myTable.setCellSelectionEnabled(true);




回答5:


Change your if(isSelected) to if (isSelected && hasFocus). This will print for only the selected cell, rather than the selected row.

mKorbel's answer should also work...



来源:https://stackoverflow.com/questions/6451200/java-how-to-select-only-one-cell-in-a-jtable-and-not-the-whole-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!