JTable:如何获取选定的单元格? [英] JTable : how to get selected cells?

查看:161
本文介绍了JTable:如何获取选定的单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

在JTable中,您拥有

In JTable, you have the

JTable.getSelectedRow()

JTable.getSelectedColumn()

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

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

这篇关于JTable:如何获取选定的单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆