Java JTable行选择

Java JTable行选择,java,swing,jtable,Java,Swing,Jtable,我需要在单击JTable上的行时选择一行。默认行为是当按下鼠标时,选中该行。我怎样才能改变这种行为?我的期望是: 鼠标按下-->鼠标释放==>选中 鼠标按下-->鼠标拖动-->鼠标释放==>未选中 鼠标单击==>选定的行 拖动鼠标时,我想做一些其他事情,但不想更改该操作上的上一行选择。我觉得这并不容易。我试图突出显示的表中的行不是当前活动的组件,因此您需要以下内容: import java.awt.event.*; import javax.swing.*; /** * * @author

我需要在单击JTable上的行时选择一行。默认行为是当按下鼠标时,选中该行。我怎样才能改变这种行为?我的期望是:

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

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

鼠标单击==>选定的行


拖动鼠标时,我想做一些其他事情,但不想更改该操作上的上一行选择。

我觉得这并不容易。我试图突出显示的表中的行不是当前活动的组件,因此您需要以下内容:

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
    }



}
// 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();
这是“stange”,但对我来说是有效的:

table.setDragEnabled(true); 

好主意,不会想到的:-)发生的是,用户界面安装了一个单独的监听器和一些逻辑来触发“正常”的东西,比如选择,只是在一个延迟之后,它试图决定是否应该将媒体视为dragStarthmm。。。刚测试:不会阻止按下按钮时的选择(这是OP的目标)