当我点击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();
这很“奇怪”,但对我来说有效:
table.setDragEnabled(true);