JTable:如何获取选定的单元格?

时间:2013-01-19 16:11:25

标签: swing jtable cell selected

我有一个JTable及其TableModel,它运行良好但我现在要做的是获取它的选定单元格。我想做类似的事情:

int rows = this.getTable().getRowCount();
int columns = this.getTable().getColumnCount();
for(int i = 0 ; i < rows ; i++)
{
    for(int j = 0 ; j < columns ; j++)
    {
         if(table.getCell(i,j).isSelected() //...
    }
}

但当然这样的事情不存在。我该怎么做呢?

4 个答案:

答案 0 :(得分:19)

在JTable中,你有

JTable.getSelectedRow()

JTable.getSelectedColumn()

您可以尝试将此两种方法与MouseListener和KeyListener结合使用。 使用KeyListener,您可以检查用户是否按下CTRL键,这意味着用户正在选择单元格,然后使用鼠标侦听器,对于您存储的每个单击,可能在Vector或ArrayList中选择单元格:

//global variables
JTable theTable = new JTable();//your table
boolean pressingCTRL=false;//flag, if pressing CTRL it is true, otherwise it is false.
Vector selectedCells = new Vector<int[]>();//int[]because every entry will store {cellX,cellY}

public void something(){
   KeyListener tableKeyListener = new KeyAdapter() {

      @Override
      public void keyPressed(KeyEvent e) {
         if(e.getKeyCode()==KeyEvent.VK_CTRL){//check if user is pressing CTRL key
            pressingCTRL=true;
         }
      }

      @Override
      public void keyReleased(KeyEvent e) {
         if(e.getKeyCode()==KeyEvent.VK_CTRL){//check if user released CTRL key
            pressingCTRL=false;
         }
      }
   };

   MouseListener tableMouseListener = new MouseAdapter() {

      @Override
      public void mouseClicked(MouseEvent e) {
         if(pressingCTRL){//check if user is pressing CTRL key
            int row = theTable.rowAtPoint(e.getPoint());//get mouse-selected row
            int col = theTable.columnAtPoint(e.getPoint());//get mouse-selected col
            int[] newEntry = new int[]{row,col};//{row,col}=selected cell
            if(selectedCells.contains(newEntry)){
               //cell was already selected, deselect it
               selectedCells.remove(newEntry);
            }else{
               //cell was not selected
               selectedCells.add(newEntry);
            }
         }
      }
   };
   theTable.addKeyListener(tableKeyListener);
   theTable.addMouseListener(tableMouseListener);
}

答案 1 :(得分:6)

table.getSelectedRow()将获得选定的行。

table.getSelectedColumns()将获得选定的列。

getValueAt(rowIndex, columnIndex)将为每列提供所选行的值。

答案 2 :(得分:3)

答案 3 :(得分:0)

您可以使用:

int row = table.rowAtPoint(e.getPoint());
int col = table.columnAtPoint(e.getPoint());

您可以使用(table.getSelectedRow()table.getSelectedColumn())获取行和列,但如果您选择了多个单元格,则方法table.getSelectedRow()table.getSelectedColumn()将返回单元格&#39;单击的第一个单元格的位置。

另一方面,table.rowAtPoint(e.getPoint())table.columnAtPoint(e.getPoint())会返回上次点击的确切单元格表格。