Source Code : JTable : how to get selected cells?

JTable : how to get selected cells?

No problem. We won't show you that ad again. Why didn't you like it?


I have a JTable and its TableModel, it works well but what I want to do now is to get the selected cells of it. I thought of doing something like :

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()//...}}

But of course something like this doesn't exist. What should I do instead?
In JTable, you have the

JTable.getSelectedRow()

and

JTable.getSelectedColumn()

You can try combine this two method with a MouseListener and a KeyListener. With the KeyListener you check if user is pressing the CTRL key, which means that user is selecting cells, then with a mouse listener, for every click you store maybe in a Vector or ArrayList the selected cells:

//global variablesJTable theTable =newJTable();//your tableboolean pressingCTRL=false;//flag, if pressing CTRL it is true, otherwise it is false.Vector selectedCells =newVector();//int[]because every entry will store {cellX,cellY}publicvoid something(){KeyListener tableKeyListener =newKeyAdapter(){@Overridepublicvoid keyPressed(KeyEvent e){if(e.getKeyCode()==KeyEvent.VK_CTRL){//check if user is pressing CTRL key
  pressingCTRL=true;}}@Overridepublicvoid keyReleased(KeyEvent e){if(e.getKeyCode()==KeyEvent.VK_CTRL){//check if user released CTRL key
  pressingCTRL=false;}}};MouseListener tableMouseListener =newMouseAdapter(){@Overridepublicvoid mouseClicked(MouseEvent e){if(pressingCTRL){//check if user is pressing CTRL keyint row = theTable.rowAtPoint(event.getPoint());//get mouse-selected rowint col = theTable.columnAtPoint(event.getPoint());//get mouse-selected colint[] newEntry =newint[]{row,col};//{row,col}=selected cellif(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);}