JTable行选择

4

当我点击JTable上的行时,我需要选择一行。默认情况下,当鼠标按下时,行会被选中。我如何更改这种行为?我的期望是:

鼠标按下 --> 鼠标释放 --> 选中

鼠标按下 --> 鼠标拖动 --> 鼠标释放 --> 不选中

鼠标单击 --> 行选中

当鼠标拖动时,我想执行其他操作,但不想在该操作中更改先前选择的行。

3个回答

6
import java.awt.event.*;
import javax.swing.*;

/**
 *
 * @author Jigar
 */
public class JTableDemo  extends MouseAdapter   {
int selection;


    public static void main(String[] args) throws Exception
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String[] headers = {"A", "B", "C"};
        Object[][] data = {{1, 2, 3}, {4, 5, 6}};
        JTable table = new JTable(data, headers);
        JScrollPane scroll = new JScrollPane();
        scroll.setViewportView(table);
        frame.add(scroll);
        frame.pack();
        frame.setVisible(true);
        table.addMouseListener(new JTableDemo());
        scroll.addMouseListener(new JTableDemo());
    }

    @Override
    public void mousePressed(MouseEvent e)
    {
        JTable jtable = (JTable) e.getSource();
        selection= jtable.getSelectedRow();
        jtable.clearSelection();
    }
    @Override
    public void mouseReleased(MouseEvent e){
        JTable jtable = (JTable) e.getSource();
        //now you need to select the row here check below link
    }



}

2

我觉得这并不是很容易。我试图在表格中突出显示行,但该表格不是当前活动组件,所以你需要类似以下的方法:

// get the selection model
ListSelectionModel tableSelectionModel = table.getSelectionModel();

// set a selection interval (in this case the first row)
tableSelectionModel.setSelectionInterval(0, 0);

// update the selection model
table.setSelectionModel(tableSelectionModel);

// repaint the table
table.repaint();

0

这很“奇怪”,但对我来说有效:

table.setDragEnabled(true); 

好主意,我想不到那个 :-) 发生的事情是UI安装了一个单独的监听器和一些逻辑来触发“正常”的东西,比如在延迟之后选择,然后尝试决定是否应该将按下视为dragStart。 - kleopatra
嗯...刚测试了一下:没有阻止按下时的选择(这是 OP 的目标)。 - kleopatra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接