当我点击JTable上的行时,我需要选择一行。默认行为是按下鼠标时,行被选中。我该如何改变这种行为?我的期望是::
鼠标按下 - >鼠标发布==>选择
鼠标按下 - >拖动鼠标 - >鼠标发布==>未选中
鼠标点击==>选择行
我想在拖动鼠标时执行其他操作,但不想更改该操作的上一行选择。
答案 0 :(得分: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
}
}
答案 1 :(得分: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();
答案 2 :(得分:0)
这是“奇怪的”,但对我来说工作:
table.setDragEnabled(true);