JTable : how to get selected cells?

人走茶凉 提交于 2019-11-29 09:56:36
BackSlash

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 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);
}

table.getSelectedRow() will get selected row.

table.getSelectedColumns() will get selected columns.

getValueAt(rowIndex, columnIndex) will give the value present at the selected row for each column.

JTable has methods to get the selected rows and get the selected columns.

You can use:

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

You can get the row and column with ( table.getSelectedRow() and table.getSelectedColumn()) but if you selected more than one cell the method table.getSelectedRow() and table.getSelectedColumn() return cell's position of the first cell that was clicked.

On the other hand, table.rowAtPoint(e.getPoint()) and table.columnAtPoint(e.getPoint()) return the exact cell's table that was clicked for the last time.

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