Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

swing - JTable : how to get selected cells?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...