![](/img/trans.png)
[英]Best Practice for Cell Editing (Single-Click or Double-Click) in Table in Swing
[英]How can I make a JTable cell do different things on single-click than on double-click?
我正在使用包含名為Subject的列的可編輯JTable
。 當第一行為空且用戶單擊主題單元格以添加新任務時,默認情況下,用戶必須單擊兩次才能使單元格可編輯。 我想讓它在單擊時可編輯,並在雙擊時打開另一個表單。 我嘗試過MouseListener
但無法解決它。 有沒有辦法解決這個問題? 如果是這樣,它是什么?
我的代碼:
class mouseRenderer extends DefaultTableCellRenderer {
JLabel lblcell = new JLabel();
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row,
int column) {
ttable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
selrow = ttable.getSelectedRow();
selcol = ttable.getSelectedColumn();
if(e.getClickCount() == 1) {
if(selrow == 0) {
lblcell.setText("");
}
}
}
});
return lblcell;
}
}
只需單擊即可編輯,您可以嘗試使用jtable中使用的celleditor的'setClickCountToStart()'方法。
您可以嘗試創建這樣的自定義CellEditor並使用setCellEditor()
public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
public boolean isCellEditable(EventObject evt) {
if (evt instanceof MouseEvent) {
int clickCount;
// For single-click activation
clickCount = 1;
// For double-click activation
clickCount = 2;
// For triple-click activation
clickCount = 3;
return ((MouseEvent)evt).getClickCount() >= clickCount;
}
return true;
}
}
MouseListener
是捕獲行上雙擊的方法。 它應該工作正常。
只需單擊即可編輯,您可能希望使用MouseMotionListener
選擇行,並讓JTable單擊進行編輯。 另一種選擇可能是使用MouseListener來檢測被單擊的單元格,但這有點混亂。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.