I have a JTable with custom editor using JTextPane for html rendering.
Also I want to edit with single click.
It works perfectly if editor component was JTextField.
But I can't edit with single click in case of JTextPane.
Because 'stopCellEditing' is called twice when I select other column.
There is one more strange thing.
When I removed all other component except JTable it works also.
//frame.add(new JTextField(), BorderLayout.SOUTH);
I know table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE); is releated this problem.
I added this function because I needed it.
I want to know why it only happens when using JTextPane and there is a workaround
Here is a full example:
public class Main {
public Main() {}
public static class MyCellEditor extends AbstractCellEditor implements TableCellEditor {
JTextComponent comp;
public MyCellEditor (JTextComponent comp) {
this.comp = comp;
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int rowIndex, int vColIndex) {
comp.setText((String)value);
return comp;
}
public Object getCellEditorValue() {
return comp.getText();
}
@Override
public boolean stopCellEditing() {
System.err.println("stopCellEditing");
return super.stopCellEditing();
}
public boolean isCellEditable(EventObject anEvent) {
if (anEvent instanceof MouseEvent) {
return ((MouseEvent)anEvent).getClickCount() >= 1;
}
return true;
}
}
public static void main(String[] args) {
String[] columnNames = {"Item", "Description"};
Object[][] data = {
{"Item 1", "Description of Item 1"},
{"Item 2", "Description of Item 2"},
{"Item 3", "Description of Item 3"}};
JTable table = new JTable(data, columnNames);
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
table.getColumnModel().getColumn(1).setPreferredWidth(300);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
//MyCellEditor myCellEditor = new MyCellEditor(new JTextField());
MyCellEditor myCellEditor = new MyCellEditor(new JTextPane());
table.getColumnModel().getColumn(1).setCellEditor(myCellEditor);
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(new JTextField(), BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}