在JTable
的实施中。我必须保留一些可编辑的列和一些可编辑的列,以便我覆盖isCellEditable
-
@Override
public boolean isCellEditable(int row, int col) {
if (col == uneditableColumn) {
return false;
}
return bEdit;
}
现在我的要求是允许仅在双击时编辑单元格,即如果用户双击单元格,则只有它进入可编辑模式。为此 - 我必须自己制作CellEditor
并覆盖。
public boolean isCellEditable( EventObject e )
有人可以建议是否可以使用 -
public boolean isCellEditable(int row, int col)
请帮忙 -
答案 0 :(得分:3)
好吧,我不会覆盖isCellEditable(...)
中的JTable
,而是提供自定义表格模型。
来自JTable#isCellEditable(...)
上的JavaDoc:
该列在表视图的显示顺序中指定,而不是在TableModel的列顺序中指定。这是一个重要的区别,因为当用户重新排列表中的列时,视图中给定索引处的列将发生更改。同时,用户的操作决不会影响模型的列排序。
此外,单元格似乎可以对表格进行编辑,但在双击之前编辑器本身可能不会提供输入字段。如果您想一次只编辑一个单元格,您也可以将该信息存储在模型中,让编辑人员检查一下。
答案 1 :(得分:3)
is to allow edit the cell only on Double click i.e. if user double clicks
on cell then only it comes into editable mode.
你看DefaultCellEditor#clickCountToStart
用于CellEditor或方法覆盖isCellEditable(AbstractTableModel)
@Override
public boolean isCellEditable(EventObject anEvent) {
if (anEvent instanceof MouseEvent) {
return ((MouseEvent) anEvent).getClickCount() >= clickCountToStart;
}
return true;
}
对于DefaultTableModel可能是
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.*;
public class EditorRendererClickCountToStart {
public EditorRendererClickCountToStart() {
TableModel model = new DefaultTableModel(new Object[][]{
{"A", "Item 0"}, {"B", "Item 1"}, {"C", "Item 2"},
{"D", "Item 3"}, {"E", "Item 4"}}, new String[]{"TextField", "Combo"});
JTable table = new JTable(model);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
DefaultCellEditor editor = new DefaultCellEditor(new JComboBox(new Object[]{
"Item 0", "Item 1", "Item 2", "Item 3", "Item 4"}));
editor.setClickCountToStart(2);
table.getColumnModel().getColumn(1).setCellEditor(editor);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
System.out.println(info.getName());
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (UnsupportedLookAndFeelException e) {// handle exception
} catch (ClassNotFoundException e) {// handle exception
} catch (InstantiationException e) {// handle exception
} catch (IllegalAccessException e) {// handle exception
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new EditorRendererClickCountToStart();
}
});
}
}