2011-02-18 61 views
4

當我點擊JTable上的行時,需要選擇一行。默認行爲是按下鼠標時,該行被選中。我怎樣才能改變這種行爲?我的期望是::JTable行選擇

鼠標按下 - >鼠標發佈==>選擇

鼠標按下 - >鼠標拖拽 - >鼠標發佈==>未選擇

鼠標單擊==>選中行

我想在拖動鼠標時執行其他操作,但不想更改該操作的上一行選擇。

回答

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

謝謝,它給我有辦法做到這一點... – 2011-02-18 09:44:27

+1

*任何幫助/指導高度讚賞。* :) – 2011-02-18 09:45:20

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

這是「STANGE」,但爲我工作:

table.setDragEnabled(true);