下面列出了怎么用javax.swing.table.TableCellEditor的API类实例代码及写法,或者点击链接到github查看源代码。
public TableColumn addColumn(Object columnIdentifier, int width,
TableCellRenderer renderer,
TableCellEditor editor, List columnData) {
checkDefaultTableModel();
// Set up the model side first
DefaultTableModel m = (DefaultTableModel)getModel();
m.addColumn(columnIdentifier, columnData.toArray());
// The column will have been added to the end, so the index of the
// column in the model is the last element.
TableColumn newColumn = new TableColumn(
m.getColumnCount()-1, width, renderer, editor);
super.addColumn(newColumn);
return newColumn;
}
public boolean editCellAt(int index, EventObject e) {
if (cellEditor != null && !cellEditor.stopCellEditing()) {
return false;
}
if (!isCellEditable(index)) {
return false;
}
TableCellEditor editor = getCellEditor(index);
if (editor != null && editor.isCellEditable(e)) {
editorComp = prepareEditor(editor, index);
editorComp.setBounds(getHeaderRect(index));
add(editorComp);
editorComp.validate();
setCellEditor(editor);
setEditingColumn(index);
editor.addCellEditorListener(this);
return true;
}
return false;
}
private void commitComponent(final Component container) {
if (container == null)
return;
if (container instanceof JTable) {
TableCellEditor cellEditor = ((JTable) container).getCellEditor();
if (cellEditor != null) {
try {
cellEditor.stopCellEditing();
} catch (Exception e) {
try {
cellEditor.cancelCellEditing();
} catch (Exception ex) {
}
}
}
}
}
@Override
public TableCellEditor getCellEditor(int row, int column) {
if ( editorFactory != null ) {
TableModel tableModel = this.getModel();
if ( tableModel != null ) {
String columnName = getColumnName(column, tableModel);
//Use original row / column index
TableCellEditor editor = this.editorFactory.getCellEditor(
row, column, columnName, tableModel, this);
if ( editor != null ) {
return editor;
}
}
}
return super.getCellEditor(row, column);
}
@Override
public final boolean editCellAt(final int row, final int column, EventObject e) {
if (LOGGER.isLoggable(Level.TRACE)) {
LOGGER.log(Level.TRACE, "editCellAt(row="+row+", col="+column+
", e="+e+")");
}
if (JConsole.isDebug()) {
System.err.println("edit: "+getValueName(row)+"="+getValue(row));
}
boolean retVal = super.editCellAt(row, column, e);
if (retVal) {
final TableCellEditor tableCellEditor =
getColumnModel().getColumn(column).getCellEditor();
if (tableCellEditor == valueCellEditor) {
((JComponent) tableCellEditor).requestFocus();
}
}
return retVal;
}
protected TableCellEditor getCellEditor(int row, int column) {
TableColumn tableColumn = impl.getColumnModel().getColumn(column);
if (tableColumn.getIdentifier() instanceof Column) {
Column columnConf = (Column) tableColumn.getIdentifier();
if (editableColumns != null
&& columnConf.getId() instanceof MetaPropertyPath
&& editableColumns.contains(columnConf.getId())) {
return tableFieldFactory.createEditComponent(row, columnConf);
}
}
return null;
}
public TableColumn addColumn(Object columnIdentifier, int width,
TableCellRenderer renderer,
TableCellEditor editor, List columnData) {
checkDefaultTableModel();
// Set up the model side first
DefaultTableModel m = (DefaultTableModel)getModel();
m.addColumn(columnIdentifier, columnData.toArray());
// The column will have been added to the end, so the index of the
// column in the model is the last element.
TableColumn newColumn = new TableColumn(
m.getColumnCount()-1, width, renderer, editor);
super.addColumn(newColumn);
return newColumn;
}
@Override
public void valueCommitted(PropertyEditor source, boolean continueEditing, boolean closeEditorOnError) {
if (isEditing()) {
Object value;
TableCellEditor tableCellEditor = cellEditor;
try {
value = tableCellEditor.getCellEditorValue();
}
catch (Exception e) {
showInvalidInput(e);
return;
}
if (setValueAtRow(editingRow, value)) {
if (!continueEditing) {
tableCellEditor.stopCellEditing();
}
}
else if (closeEditorOnError) {
tableCellEditor.cancelCellEditing();
}
}
}
@Override
public TableCellEditor getCellEditor(int row, int column) {
if (column == 0) { // RowNo.
if (row == IS_SELECTED_ROW) {
return globalCheckBoxCellEditor;
}
return super.getCellEditor();
}
column--;
if (row == VALUE_TYPE_ROW) {
return valueTypeCellEditor;
}
if (row == IS_SELECTED_ROW) {
return checkBoxCellEditor;
}
if (row == ROLE_ROW) {
return roleCellEditor;
}
// ATTRIBUTE_NAME_ROW
return super.getCellEditor(row, column);
}
@Test
public void testEditName() throws Exception {
table.addRowSelectionInterval(0, 0);
Rectangle rect = table.getCellRect(0, MemoryMapModel.NAME, true);
clickMouse(table, 1, rect.x, rect.y, 2, 0);
waitForPostedSwingRunnables();
SwingUtilities.invokeAndWait(() -> {
int row = 0;
TableCellEditor editor = table.getCellEditor(row, MemoryMapModel.NAME);
Component c = editor.getTableCellEditorComponent(table,
model.getValueAt(row, MemoryMapModel.NAME), true, row, MemoryMapModel.NAME);
JTextField tf = (JTextField) c;
tf.setText(".test");
editor.stopCellEditing();
});
waitForPostedSwingRunnables();
assertEquals(".test", model.getValueAt(0, MemoryMapModel.NAME));
}
@Override
public final boolean editCellAt(final int row, final int column, EventObject e) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("editCellAt(row="+row+", col="+column+
", e="+e+")");
}
if (JConsole.isDebug()) {
System.err.println("edit: "+getValueName(row)+"="+getValue(row));
}
boolean retVal = super.editCellAt(row, column, e);
if (retVal) {
final TableCellEditor tableCellEditor =
getColumnModel().getColumn(column).getCellEditor();
if (tableCellEditor == valueCellEditor) {
((JComponent) tableCellEditor).requestFocus();
}
}
return retVal;
}
/**
* Gets map of all declined word forms. Key = combined ID, value = word form
* @return
*/
@Override
public Map<String, String> getAllDecValues() {
Map<String, String> ret = new HashMap<>();
TableCellEditor editor = table.getCellEditor();
if (editor != null) {
editor.stopCellEditing();
}
decIdsToGridLocation.entrySet().forEach((entry) -> {
Object val = table.getModel().getValueAt(entry.getValue().height, entry.getValue().width);
ret.put(entry.getKey(), val == null ? "" : (String)val);
});
return ret;
}
@Override
public Component prepareEditor(TableCellEditor editor, int row, int column) {
Component result = super.prepareEditor(editor, row, column);
if (result instanceof JTextComponent) {
Object textFieldFont = UIManager.get("TextField.font");
if (textFieldFont instanceof Font) {
result.setFont((Font) textFieldFont);
}
if (Boolean.TRUE == getClientProperty("GPTreeTableBase.clearText")) {
((JTextComponent) result).setText("");
}
if (Boolean.TRUE == getClientProperty("GPTreeTableBase.selectAll")) {
SwingUtilities.invokeLater(TreeTableCellEditorImpl.createSelectAllCommand((JTextComponent) result));
}
if (Boolean.TRUE == getClientProperty("GPTreeTableBase.unselectAll")) {
SwingUtilities.invokeLater(TreeTableCellEditorImpl.createUnselectAllCommand((JTextComponent) result));
putClientProperty("GPTreeTableBase.unselectAll", false);
}
}
return result;
}
private static Pair<JLabel, ? extends TableCellEditor> createDateValidatorComponents(final String hint, DateFormat... dateFormats) {
Supplier<List<DateFormat>> formatSupplier = Suppliers.<List<DateFormat>>ofInstance(Lists.newArrayList(dateFormats));
final JLabel hintLabel = new JLabel(" "); // non-empty label to occupy some vertical space
final ValueValidator<Date> realValidator = UIUtil.createStringDateValidator(null, formatSupplier);
ValueValidator<Date> decorator = new ValueValidator<Date>() {
@Override
public Date parse(String text) throws ValidationException {
try {
Date result = realValidator.parse(text);
hintLabel.setText("");
return result;
} catch (ValidationException e) {
e.printStackTrace();
hintLabel.setText(hint);
throw e;
}
}
};
GPDateCellEditor dateEditor = new GPDateCellEditor(null, true, decorator, formatSupplier);
return Pair.create(hintLabel, dateEditor);
}
private TableCellEditor getEditor(final Object value) {
if (value instanceof Number) {
return spinnerEditor.get();
} else {
return getDelegate();
}
}
private void cancelEditor() {
if (getInplaceEditor() != null) {
java.awt.Container parent = getParent();
while (parent != null && !(parent instanceof javax.swing.JTable)) {
parent = parent.getParent();
}
if (parent != null) {
TableCellEditor tce = ((javax.swing.JTable) parent).getCellEditor();
if (tce != null) {
tce.cancelCellEditing();
}
}
}
}
public void setData( final Element[] elements ) {
final TableCellEditor tableCellEditor = table.getCellEditor();
if ( tableCellEditor != null ) {
tableCellEditor.stopCellEditing();
}
dataModel.setData( elements );
}
public static void main(String[] args) throws Exception {
KeyboardFocusManager.getCurrentKeyboardFocusManager();
System.setSecurityManager(new AppletSecurity());
JTable table = new JTable();
TableCellEditor de = table.getDefaultEditor(Double.class);
if (de == null) {
throw new RuntimeException("Table default editor is null");
}
}
@Override
public boolean stopCellEditing() {
if (currentEditor != null) {
boolean status = currentEditor.stopCellEditing();
if (status) {
canceledEditorRef = new WeakReference<TableCellEditor>(currentEditor);
currentEditor = null;
}
return status;
}
return true;
}
public void cancelCellEditing() {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("Cancel Editing Row: "+getEditingRow());
}
final TableCellEditor tableCellEditor = getCellEditor();
if (tableCellEditor != null) {
tableCellEditor.cancelCellEditing();
}
}
public void editingStopped(ChangeEvent e) {
TableCellEditor editor = getCellEditor();
if (editor != null) {
Object value = editor.getCellEditorValue();
int index = getEditingColumn();
columnModel.getColumn(index).setHeaderValue(value);
removeEditor();
}
}
/**
* Close the combo box on the selected row of the field table
* @param inRow currently selected row number
*/
private void closeTableComboBox(int inRow)
{
TableCellEditor editor = _fieldTable.getCellEditor(inRow, 1);
if (editor != null)
{
editor.stopCellEditing();
}
}
public void stopCellEditing() {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("Stop Editing Row: "+getEditingRow());
}
final TableCellEditor tableCellEditor = getCellEditor();
if (tableCellEditor != null) {
tableCellEditor.stopCellEditing();
}
}
/**
* Cancels on-going cell editing
*/
public void cancelEditing() {
TableCellEditor editor = getCellEditor();
if (editor != null) {
editor.cancelCellEditing();
}
}
public Component prepareEditor(TableCellEditor editor, int row, int column) {
Component c = super.prepareEditor(editor, row, column);
c.setForeground(getSelectionForeground());
c.setBackground(getSelectionBackground());
return c;
}
@Override
public void editingStopped(ChangeEvent e) {
TableCellEditor editor = getCellEditor();
if (editor != null) {
Object value = editor.getCellEditorValue();
int index = getEditingColumn();
columnModel.getColumn(index).setHeaderValue(value);
removeEditor();
}
}
@Override
public Component prepareEditor(TableCellEditor editor, int row, int column) {
Component component = super.prepareEditor(editor, row, column);
if (component != null && !"Storage".equals(getColumnName(column))) {
component.removeFocusListener(focusListener);
component.addFocusListener(focusListener);
}
return component;
}
private static JTable makeTable(TableModel model) {
return new JTable(model) {
@Override public void updateUI() {
// [JDK-6788475] Changing to Nimbus LAF and back doesn't reset look and feel of JTable completely - Java Bug System
// https://bugs.openjdk.java.net/browse/JDK-6788475
// XXX: set dummy ColorUIResource
setSelectionForeground(new ColorUIResource(Color.RED));
setSelectionBackground(new ColorUIResource(Color.RED));
super.updateUI();
updateRenderer();
JCheckBox checkBox = makeBooleanEditor(this);
setDefaultEditor(Boolean.class, new DefaultCellEditor(checkBox));
}
private void updateRenderer() {
TableModel m = getModel();
for (int i = 0; i < m.getColumnCount(); i++) {
TableCellRenderer r = getDefaultRenderer(m.getColumnClass(i));
if (r instanceof Component) {
SwingUtilities.updateComponentTreeUI((Component) r);
}
}
}
@Override public Component prepareEditor(TableCellEditor editor, int row, int column) {
Component c = super.prepareEditor(editor, row, column);
if (c instanceof JCheckBox) {
JCheckBox b = (JCheckBox) c;
b.setBackground(getSelectionBackground());
b.setBorderPainted(true);
}
return c;
}
};
}
/**
* Creates a combobox for a cell editor.
*
* @return the combobox that is used as the editor.
*/
public JComboBox setChoices(int row, int col, String[] choices,
boolean editable) {
TableCellEditor ed = new ComboBoxTableCellEditor(choices);
cellEditors[row][col] = ed;
// if the table is editable, we should turn off the [...] editor
// when there's a choice on the row.
data[row][2]=NbBundle.getBundle(DisplayTable.class).getString("MON_Editing");
cellEditors[row][2] = null;
return ((ComboBoxTableCellEditor)ed).getComboBox();
}
/** Overridden to set the colors apropriately - we always want the editor
* to appear selected */
@Override
public Component prepareEditor(TableCellEditor editor, int row, int col) {
if (editor == null) {
return null;
}
Component result = super.prepareEditor(editor, row, col);
if (result == null) {
return null;
}
if( 1 == col ) {
//Usually result == ine, but custom impls may not be
InplaceEditor ine = getEditor().getInplaceEditor();
if (ine.supportsTextEntry()) {
result.setBackground(PropUtils.getTextFieldBackground());
result.setForeground(PropUtils.getTextFieldForeground());
}
}
if (result instanceof JComponent) {
//unlikely that it won't be
((JComponent) result).setBorder(BorderFactory.createEmptyBorder(0, PropUtils.getTextMargin(), 0, 0));
}
return result;
}