Java Tutorial/Swing/JTable Renderer Editor
Содержание
- 1 An Editor for the Gender Column
- 2 Cell Renderer for the Gender Column
- 3 ColorChooserEditor
- 4 Creating a Class-Based Custom Cell Renderer in a JTable Component
- 5 Creating a Custom Cell Renderer in a JTable Component
- 6 Default Editors and Renderers
- 7 Demonstrates the editable property of Swing tables.
- 8 Discard any changes made by the user and stops the editing process
- 9 Editing Table Cells: JComboBox As Table Cell Renderer
- 10 extends DefaultCellEditor
- 11 Get Default Cell Editor
- 12 Get Default cell Renderer
- 13 implements TableCellRenderer
- 14 Preventing Invalid Values in a Cell in a JTable Component
- 15 Rendering Table Cells: To install the renderer as the default renderer for the JTable for Object.class
- 16 Save the current value in the cell being edited and stops the editing process
- 17 Using a JComboBox in a Cell in a JTable Component
- 18 Using a List JSpinner as a Cell Editor in a JTable Component
- 19 Using Built-In Cell Renderers and Editors in a JTable Component
- 20 Using default Boolean value cell editor and renderer
An Editor for the Gender Column
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.EventObject;
import java.util.GregorianCalendar;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.EventListenerList;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
class GenderEditor extends JComboBox implements TableCellEditor {
protected EventListenerList listenerList = new EventListenerList();
protected ChangeEvent changeEvent = new ChangeEvent(this);
public GenderEditor() {
super();
addItem("Male");
addItem("Female");
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
fireEditingStopped();
}
});
}
public void addCellEditorListener(CellEditorListener listener) {
listenerList.add(CellEditorListener.class, listener);
}
public void removeCellEditorListener(CellEditorListener listener) {
listenerList.remove(CellEditorListener.class, listener);
}
protected void fireEditingStopped() {
CellEditorListener listener;
Object[] listeners = listenerList.getListenerList();
for (int i = 0; i < listeners.length; i++) {
if (listeners[i] == CellEditorListener.class) {
listener = (CellEditorListener) listeners[i + 1];
listener.editingStopped(changeEvent);
}
}
}
protected void fireEditingCanceled() {
CellEditorListener listener;
Object[] listeners = listenerList.getListenerList();
for (int i = 0; i < listeners.length; i++) {
if (listeners[i] == CellEditorListener.class) {
listener = (CellEditorListener) listeners[i + 1];
listener.editingCanceled(changeEvent);
}
}
}
public void cancelCellEditing() {
fireEditingCanceled();
}
public boolean stopCellEditing() {
fireEditingStopped();
return true;
}
public boolean isCellEditable(EventObject event) {
return true;
}
public boolean shouldSelectCell(EventObject event) {
return true;
}
public Object getCellEditorValue() {
return new Boolean(getSelectedIndex() == 0 ? true : false);
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
int row, int column) {
boolean isMale = ((Boolean) value).booleanValue();
setSelectedIndex(isMale ? 0 : 1);
return this;
}
}
public class TableCellEditorJComboBox extends JFrame {
protected JTable table;
public static void main(String[] args) {
TableCellEditorJComboBox stt = new TableCellEditorJComboBox();
stt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
stt.setSize(400, 200);
stt.setVisible(true);
}
public TableCellEditorJComboBox() {
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
TableValues tv = new TableValues();
table = new JTable(tv);
TableColumnModel tcm = table.getColumnModel();
TableColumn tc = tcm.getColumn(TableValues.GENDER);
tc.setCellEditor(new GenderEditor());
JScrollPane jsp = new JScrollPane(table);
pane.add(jsp, BorderLayout.CENTER);
}
}
class TableValues extends AbstractTableModel {
public final static int FIRST_NAME = 0;
public final static int LAST_NAME = 1;
public final static int DATE_OF_BIRTH = 2;
public final static int ACCOUNT_BALANCE = 3;
public final static int GENDER = 4;
public final static boolean GENDER_MALE = true;
public final static boolean GENDER_FEMALE = false;
public Object[][] values = {
{ "C", "A", new GregorianCalendar(1962, Calendar.FEBRUARY, 20).getTime(), new Float(1.67),
new Boolean(GENDER_MALE) },
{ "J", "A", new GregorianCalendar(1987, Calendar.JANUARY, 6).getTime(), new Float(2.78),
new Boolean(GENDER_MALE) },
{ "J", "A", new GregorianCalendar(1989, Calendar.AUGUST, 31).getTime(), new Float(3.89),
new Boolean(GENDER_FEMALE) },
{ "E", "K", new GregorianCalendar(1945, Calendar.JANUARY, 16).getTime(), new Float(-4.70),
new Boolean(GENDER_FEMALE) },
{ "B", "S", new GregorianCalendar(1907, Calendar.AUGUST, 2).getTime(), new Float(5.00),
new Boolean(GENDER_FEMALE) } };
public int getRowCount() {
return values.length;
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
public int getColumnCount() {
return values[0].length;
}
public Object getValueAt(int row, int column) {
return values[row][column];
}
}
Cell Renderer for the Gender Column
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Container;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
class GenderRenderer extends JComboBox implements TableCellRenderer {
public GenderRenderer() {
super();
addItem("Male");
addItem("Female");
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
boolean isMale = ((Boolean) value).booleanValue();
setSelectedIndex(isMale ? 0 : 1);
return this;
}
}
public class TableCellRendererJComboBox extends JFrame {
protected JTable table;
public static void main(String[] args) {
TableCellRendererJComboBox stt = new TableCellRendererJComboBox();
stt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
stt.setSize(400, 200);
stt.setVisible(true);
}
public TableCellRendererJComboBox() {
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
TableValues tv = new TableValues();
table = new JTable(tv);
TableColumnModel tcm = table.getColumnModel();
TableColumn tc = tcm.getColumn(TableValues.GENDER);
tc.setCellRenderer(new GenderRenderer());
JScrollPane jsp = new JScrollPane(table);
pane.add(jsp, BorderLayout.CENTER);
}
}
class TableValues extends AbstractTableModel {
public final static int FIRST_NAME = 0;
public final static int LAST_NAME = 1;
public final static int DATE_OF_BIRTH = 2;
public final static int ACCOUNT_BALANCE = 3;
public final static int GENDER = 4;
public final static boolean GENDER_MALE = true;
public final static boolean GENDER_FEMALE = false;
public Object[][] values = {
{ "C", "A", new GregorianCalendar(1962, Calendar.FEBRUARY, 20).getTime(),
new Float(1.67), new Boolean(GENDER_MALE) },
{ "J", "A", new GregorianCalendar(1987, Calendar.JANUARY, 6).getTime(),
new Float(2.78), new Boolean(GENDER_MALE) },
{ "J", "A", new GregorianCalendar(1989, Calendar.AUGUST, 31).getTime(),
new Float(3.89), new Boolean(GENDER_FEMALE) },
{ "E", "K", new GregorianCalendar(1945, Calendar.JANUARY, 16).getTime(),
new Float(-4.70), new Boolean(GENDER_FEMALE) },
{ "B", "S", new GregorianCalendar(1907, Calendar.AUGUST, 2).getTime(),
new Float(5.00), new Boolean(GENDER_FEMALE) } };
public int getRowCount() {
return values.length;
}
public int getColumnCount() {
return values[0].length;
}
public Object getValueAt(int row, int column) {
return values[row][column];
}
}
ColorChooserEditor
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
class ColorTableModel extends AbstractTableModel {
Object rowData[][] = { { "1", Color.RED }, { "2", Color.BLUE }, { "3", Color.GREEN } };
String columnNames[] = { "English", "Color" };
public int getColumnCount() {
return columnNames.length;
}
public String getColumnName(int column) {
return columnNames[column];
}
public int getRowCount() {
return rowData.length;
}
public Object getValueAt(int row, int column) {
return rowData[row][column];
}
public Class getColumnClass(int column) {
return (getValueAt(0, column).getClass());
}
public void setValueAt(Object value, int row, int column) {
rowData[row][column] = value;
}
public boolean isCellEditable(int row, int column) {
return (column != 0);
}
}
class ColorChooserEditor extends AbstractCellEditor implements TableCellEditor {
private JButton delegate = new JButton();
Color savedColor;
public ColorChooserEditor() {
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
Color color = JColorChooser.showDialog(delegate, "Color Chooser", savedColor);
ColorChooserEditor.this.changeColor(color);
}
};
delegate.addActionListener(actionListener);
}
public Object getCellEditorValue() {
return savedColor;
}
private void changeColor(Color color) {
if (color != null) {
savedColor = color;
delegate.setBackground(color);
}
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
int row, int column) {
changeColor((Color) value);
return delegate;
}
}
public class ChooserTableSample {
public static void main(String args[]) {
JFrame frame = new JFrame("Editable Color Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableModel model = new ColorTableModel();
JTable table = new JTable(model);
TableColumn column = table.getColumnModel().getColumn(3);
TableCellEditor editor = new ColorChooserEditor();
column.setCellEditor(editor);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
Creating a Class-Based Custom Cell Renderer in a JTable Component
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class Main {
public static void main(String[] argv) {
DefaultTableModel model = new DefaultTableModel() {
public Class getColumnClass(int mColIndex) {
int rowIndex = 0;
Object o = getValueAt(rowIndex, mColIndex);
if (o == null) {
return Object.class;
} else {
return o.getClass();
}
}
};
JTable table = new JTable(model);
model.addColumn("Col1", new Object[] { Color.red });
model.addRow(new Object[] { Color.green });
model.addRow(new Object[] { Color.blue });
table.setDefaultRenderer(Color.class, new ColorTableCellRenderer());
JFrame f = new JFrame();
f.setSize(300,300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
class ColorTableCellRenderer extends JLabel implements TableCellRenderer {
Color curColor;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int rowIndex, int vColIndex) {
if (curColor instanceof Color) {
curColor = (Color) value;
} else {
curColor = table.getBackground();
}
return this;
}
public void paint(Graphics g) {
g.setColor(curColor);
g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
}
}
Creating a Custom Cell Renderer in a JTable Component
import java.awt.ruponent;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
int vColIndex = 0;
TableColumn col = table.getColumnModel().getColumn(vColIndex);
col.setCellRenderer(new MyTableCellRenderer());
}
}
class MyTableCellRenderer extends JLabel implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int rowIndex, int vColIndex) {
setText(value.toString());
setToolTipText((String) value);
return this;
}
}
Default Editors and Renderers
Data TypeRendererBooleanrendered with a check box.Numberrendered by a right-aligned label.Double, Floatrendered by a right-aligned label, using the default number format.Daterendered by a label, using a short style.ImageIcon, Iconrendered by a centered label.Objectrendered by a label that displays the object"s string value.
Demonstrates the editable property of Swing tables.
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
public class EditableTable {
public static void main(String[] a) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] columnTitles = { "First Name", "Last Name", "Weight (lb)", "Blood Group", "Age>20yrs" };
Object[][] dataEntries = { { "Saravan", "Pantham", new Integer(50), "B", new Boolean(false) },
{ "Eric", "", new Integer(180), "O", new Boolean(true) },
{ "John", "", new Integer(120), "AB", new Boolean(false) },
{ "Mathew", "", new Integer(140), "A", new Boolean(true) }, };
TableModel model = new EditableTableModel(columnTitles, dataEntries);
JTable table = new JTable(model);
table.createDefaultColumnsFromModel();
String[] bloodGroups = { "A", "B", "AB", "O" };
JComboBox comboBox = new JComboBox(bloodGroups);
table.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(comboBox));
frame.add(new JScrollPane(table));
frame.setSize(300, 200);
frame.setVisible(true);
}
}
class EditableTableModel extends AbstractTableModel {
String[] columnTitles;
Object[][] dataEntries;
int rowCount;
public EditableTableModel(String[] columnTitles, Object[][] dataEntries) {
this.columnTitles = columnTitles;
this.dataEntries = dataEntries;
}
public int getRowCount() {
return dataEntries.length;
}
public int getColumnCount() {
return columnTitles.length;
}
public Object getValueAt(int row, int column) {
return dataEntries[row][column];
}
public String getColumnName(int column) {
return columnTitles[column];
}
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
public boolean isCellEditable(int row, int column) {
return true;
}
public void setValueAt(Object value, int row, int column) {
dataEntries[row][column] = value;
}
}
Discard any changes made by the user and stops the editing process
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(true);
int row = 1;
int col = 3;
boolean success = table.editCellAt(row, col);
if (success) {
boolean toggle = false;
boolean extend = false;
table.changeSelection(row, col, toggle, extend);
}
if (table.getCellEditor() != null) {
table.getCellEditor().cancelCellEditing();
}
}
}
Editing Table Cells: JComboBox As Table Cell Renderer
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
class ComboTableCellRenderer implements ListCellRenderer, TableCellRenderer {
DefaultListCellRenderer listRenderer = new DefaultListCellRenderer();
DefaultTableCellRenderer tableRenderer = new DefaultTableCellRenderer();
private void configureRenderer(JLabel renderer, Object value) {
if ((value != null) && (value instanceof Color)) {
renderer.setText(value.toString());
renderer.setBackground((Color)value);
} else {
renderer.setText((String) value);
}
}
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
listRenderer = (DefaultListCellRenderer) listRenderer.getListCellRendererComponent(list, value,
index, isSelected, cellHasFocus);
configureRenderer(listRenderer, value);
return listRenderer;
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
tableRenderer = (DefaultTableCellRenderer) tableRenderer.getTableCellRendererComponent(table,
value, isSelected, hasFocus, row, column);
configureRenderer(tableRenderer, value);
return tableRenderer;
}
}
class ColorTableModel extends AbstractTableModel {
Object rowData[][] = { { "1", Color.RED },
{ "2", Color.BLUE },
{ "3", Color.GREEN },
{ "4", Color.MAGENTA },
{ "5", Color.PINK }, };
String columnNames[] = { "English","Color" };
public int getColumnCount() {
return columnNames.length;
}
public String getColumnName(int column) {
return columnNames[column];
}
public int getRowCount() {
return rowData.length;
}
public Object getValueAt(int row, int column) {
return rowData[row][column];
}
public Class getColumnClass(int column) {
return (getValueAt(0, column).getClass());
}
public void setValueAt(Object value, int row, int column) {
rowData[row][column] = value;
}
public boolean isCellEditable(int row, int column) {
return (column != 0);
}
}
public class EditableColorColumn {
public static void main(String args[]) {
Color choices[] = { Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE,
Color.MAGENTA };
ComboTableCellRenderer renderer = new ComboTableCellRenderer();
JComboBox comboBox = new JComboBox(choices);
comboBox.setRenderer(renderer);
TableCellEditor editor = new DefaultCellEditor(comboBox);
JFrame frame = new JFrame("Editable Color Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableModel model = new ColorTableModel();
JTable table = new JTable(model);
TableColumn column = table.getColumnModel().getColumn(1);
column.setCellRenderer(renderer);
column.setCellEditor(editor);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
extends DefaultCellEditor
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Font;
import javax.swing.DefaultCellEditor;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
public class DefaultCellEditorJTextFieldAlignment extends JFrame {
DefaultTableModel model = new DefaultTableModel(new Object[][] { { "some", "text" },
{ "any", "text" }, { "even", "more" }, { "text", "strings" }, { "and", "other" },
{ "text", "values" } }, new Object[] { "Column 1", "Column 2" });
public DefaultCellEditorJTextFieldAlignment() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table = new JTable(model);
table.setDefaultEditor(Object.class, new MyEditor());
getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
pack();
}
public static void main(String arg[]) {
new DefaultCellEditorJTextFieldAlignment().setVisible(true);
}
}
class MyEditor extends DefaultCellEditor {
public MyEditor() {
super(new JTextField());
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
int row, int column) {
JTextField editor = (JTextField) super.getTableCellEditorComponent(table, value, isSelected,
row, column);
if (value != null)
editor.setText(value.toString());
if (column == 0) {
editor.setHorizontalAlignment(SwingConstants.CENTER);
editor.setFont(new Font("Serif", Font.BOLD, 14));
} else {
editor.setHorizontalAlignment(SwingConstants.RIGHT);
editor.setFont(new Font("Serif", Font.ITALIC, 12));
}
return editor;
}
}
Get Default Cell Editor
import java.util.Date;
import java.util.Enumeration;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class Main {
public static void main(String[] argv) {
DefaultTableModel model = new DefaultTableModel() {
public Class getColumnClass(int columnIndex) {
Object o = getValueAt(0, columnIndex);
if (o == null) {
return Object.class;
} else {
return o.getClass();
}
}
};
JTable table = new JTable(model);
model.addColumn("Boolean", new Object[] { Boolean.TRUE });
model.addColumn("Date", new Object[] { new Date() });
model.addColumn("Double", new Object[] { new Double(Math.PI) });
model.addColumn("Float", new Object[] { new Float(1.2) });
model.addColumn("Icon", new Object[] { new ImageIcon("icon.gif") });
model.addColumn("Number", new Object[] { new Integer(1) });
model.addColumn("Object", new Object[] { "object" });
Enumeration e = table.getColumnModel().getColumns();
TableColumn col = (TableColumn) e.nextElement();
col.setCellRenderer(table.getDefaultRenderer(Boolean.class));
col.setCellEditor(table.getDefaultEditor(Boolean.class));
JFrame f = new JFrame();
f.setSize(300,300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Get Default cell Renderer
import java.util.Date;
import java.util.Enumeration;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class Main {
public static void main(String[] argv) {
DefaultTableModel model = new DefaultTableModel() {
public Class getColumnClass(int columnIndex) {
Object o = getValueAt(0, columnIndex);
if (o == null) {
return Object.class;
} else {
return o.getClass();
}
}
};
JTable table = new JTable(model);
model.addColumn("Boolean", new Object[] { Boolean.TRUE });
model.addColumn("Date", new Object[] { new Date() });
model.addColumn("Double", new Object[] { new Double(Math.PI) });
model.addColumn("Float", new Object[] { new Float(1.2) });
model.addColumn("Icon", new Object[] { new ImageIcon("icon.gif") });
model.addColumn("Number", new Object[] { new Integer(1) });
model.addColumn("Object", new Object[] { "object" });
Enumeration e = table.getColumnModel().getColumns();
TableColumn col = (TableColumn) e.nextElement();
col.setCellRenderer(table.getDefaultRenderer(Boolean.class));
col.setCellEditor(table.getDefaultEditor(Boolean.class));
JFrame f = new JFrame();
f.setSize(300,300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
implements TableCellRenderer
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class EvenOddRowCellRenderer extends JFrame {
DefaultTableModel tmodel = new DefaultTableModel(new Object[][] { { "some", "text" },
{ "any", "text" }, { "even", "more" }, { "text", "strings" }, { "and", "other" },
{ "text", "values" } }, new Object[] { "Column 1", "Column 2" });
public EvenOddRowCellRenderer() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table = new JTable(tmodel);
table.setDefaultRenderer(Object.class, new MyRenderer());
getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
pack();
}
public static void main(String arg[]) {
new EvenOddRowCellRenderer().setVisible(true);
}
}
class MyRenderer implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
JTextField editor = new JTextField();
if (value != null)
editor.setText(value.toString());
editor.setBackground((row % 2 == 0) ? Color.white : Color.cyan);
return editor;
}
}
Preventing Invalid Values in a Cell in a JTable Component
import java.awt.ruponent;
import javax.swing.AbstractCellEditor;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
TableColumn col = table.getColumnModel().getColumn(0);
col.setCellEditor(new MyTableCellEditor());
}
}
class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
public boolean stopCellEditing() {
String s = (String) getCellEditorValue();
return super.stopCellEditing();
}
JTextField field = new JTextField();
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
return field;
}
public Object getCellEditorValue() {
return null;
}
}
Rendering Table Cells: To install the renderer as the default renderer for the JTable for Object.class
Renderers for tables can be installed for individual classes or for specific columns.
TableCellRenderer renderer = new EvenOddRenderer();
table.setDefaultRenderer(Object.class, renderer);
Save the current value in the cell being edited and stops the editing process
import javax.swing.JTable;
public class Main {
public static void main(String[] argv) throws Exception {
int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
// Enable the ability to select a single cell
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(true);
if (table.getCellEditor() != null) {
table.getCellEditor().stopCellEditing();
}
}
}
Using a JComboBox in a Cell in a JTable Component
import java.awt.ruponent;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addColumn("A", new Object[] { "item1" });
model.addColumn("B", new Object[] { "item2" });
String[] values = new String[] { "1", "2", "3" };
TableColumn col = table.getColumnModel().getColumn(0);
col.setCellEditor(new MyComboBoxEditor(values));
col.setCellRenderer(new MyComboBoxRenderer(values));
}
}
class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
public MyComboBoxRenderer(String[] items) {
super(items);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setSelectedItem(value);
return this;
}
}
class MyComboBoxEditor extends DefaultCellEditor {
public MyComboBoxEditor(String[] items) {
super(new JComboBox(items));
}
}
Using a List JSpinner as a Cell Editor in a JTable Component
import java.awt.ruponent;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.EventObject;
import javax.swing.AbstractCellEditor;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.SpinnerListModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
public class Main {
public static void main(String[] argv) throws Exception {
JTable table = new JTable();
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addColumn("A", new Object[] { "item1" });
model.addColumn("B", new Object[] { "item2" });
String[] values = new String[] { "1", "2", "3" };
TableColumn col = table.getColumnModel().getColumn(0);
col.setCellEditor(new SpinnerEditor(values));
}
}
class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
final JSpinner spinner = new JSpinner();
public SpinnerEditor(String[] items) {
spinner.setModel(new SpinnerListModel(Arrays.asList(items)));
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
int row, int column) {
spinner.setValue(value);
return spinner;
}
public boolean isCellEditable(EventObject evt) {
if (evt instanceof MouseEvent) {
return ((MouseEvent) evt).getClickCount() >= 2;
}
return true;
}
public Object getCellEditorValue() {
return spinner.getValue();
}
}
Using Built-In Cell Renderers and Editors in a JTable Component
import java.util.Date;
import java.util.Enumeration;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class Main {
public static void main(String[] argv) {
DefaultTableModel model = new DefaultTableModel() {
public Class getColumnClass(int columnIndex) {
Object o = getValueAt(0, columnIndex);
if (o == null) {
return Object.class;
} else {
return o.getClass();
}
}
};
JTable table = new JTable(model);
model.addColumn("Boolean", new Object[] { Boolean.TRUE });
model.addColumn("Date", new Object[] { new Date() });
model.addColumn("Double", new Object[] { new Double(Math.PI) });
model.addColumn("Float", new Object[] { new Float(1.2) });
model.addColumn("Icon", new Object[] { new ImageIcon("icon.gif") });
model.addColumn("Number", new Object[] { new Integer(1) });
model.addColumn("Object", new Object[] { "object" });
JFrame f = new JFrame();
f.setSize(300,300);
f.add(new JScrollPane(table));
f.setVisible(true);
}
}
Using default Boolean value cell editor and renderer
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
class ColorTableModel extends AbstractTableModel {
Object rowData[][] = { { "1", Boolean.TRUE }, { "2", Boolean.TRUE }, { "3", Boolean.FALSE },
{ "4", Boolean.TRUE }, { "5", Boolean.FALSE }, };
String columnNames[] = { "English", "Boolean" };
public int getColumnCount() {
return columnNames.length;
}
public String getColumnName(int column) {
return columnNames[column];
}
public int getRowCount() {
return rowData.length;
}
public Object getValueAt(int row, int column) {
return rowData[row][column];
}
public Class getColumnClass(int column) {
return (getValueAt(0, column).getClass());
}
public void setValueAt(Object value, int row, int column) {
rowData[row][column] = value;
}
public boolean isCellEditable(int row, int column) {
return (column != 0);
}
}
public class EditableColorColumn {
public static void main(String args[]) {
JFrame frame = new JFrame("Editable Color Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableModel model = new ColorTableModel();
JTable table = new JTable(model);
// TableColumn column = table.getColumnModel().getColumn(3);
// column.setCellRenderer(renderer);
// column.setCellEditor(editor);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}