我有一個JTable
自定義渲染器。點擊JTable
中的某個項目時,我執行一系列影響模型的特定操作。我有兩個選擇來實現這一點:在JTable中使用JButton&Action有什麼缺點?
ListSelectionListener :我在我的整個JTable
其中火添加監聽單擊某一行的時候。然後我執行這些操作。
- 優點:可以讓我選擇行(對我來說不是必需的)的任何部分,可能是擺方式試圖事件是火一個
JTable
- 缺點:我要創建一個自定義類來處理這個和重現代碼。
實施例:
class Selector implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent event) {
// ... write the action code here
}
}
的JButton &行動 :我渲染JButton
並添加Action
到JButton
。
- 優點:我可以重複使用
Action
,如果我改變Action
,使用它的所有實例將被更新。 - 缺點:我將邏輯移到我的渲染代碼中。
例子:
class Renderer implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int col) {
JButton btn = new JButton(value.toString());
btn.setAction(new SpecificAction());
return btn;
}
}
如果我用的是第二種方案,將火雨從天上下來?
他們都是同樣可行的嗎?
有沒有辦法在
ListSelectionListener
內使用Action
?
你有沒有考慮創建一個CellEditor的,而不是來執行代碼? – 2013-02-19 19:42:52
@JonathanDrapeau我沒有提到CellEditor,但你沒錯,選項2需要實現CellEditor來實際觸發Action。我選擇添加一個匿名ListSelectionListener並手動創建/激發Action。 – sdasdadas 2013-02-19 19:57:00