你可以stopEditing()
在TableCellEditor
或者直接写
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
更复杂的(JFormattedTextField)示例
import java.awt.Component;
import java.awt.EventQueue;
import java.text.DecimalFormat;
import java.text.ParseException;
import javax.swing.*;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;
public class EditorAsRendererTableTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JTable table = new JTable(3, 2);
TableColumnModel colModel = table.getColumnModel();
MyCellEditor both = new MyCellEditor();
colModel.getColumn(0).setCellEditor(both);
colModel.getColumn(0).setCellRenderer(both);
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private static class MyCellEditor extends AbstractCellEditor implements TableCellEditor, TableCellRenderer {
private static final long serialVersionUID = 1L;
private JFormattedTextField renderer = new JFormattedTextField(DecimalFormat.getInstance());
private JFormattedTextField editor;
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
renderer.setValue(value);
return renderer;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
editor = new JFormattedTextField(DecimalFormat.getInstance());
editor.setValue(value);
return editor;
}
@Override
public boolean stopCellEditing() {
try {
editor.commitEdit();
} catch (ParseException e) {
return false;
}
return super.stopCellEditing();
}
@Override
public Object getCellEditorValue() {
return editor.getValue();
}
}
private EditorAsRendererTableTest() {
}
}