📄 e929. creating a class-based custom cell renderer in a jtable component.txt
字号:
See e928 Creating a Custom Cell Renderer in a JTable Component for information on how to implement a custom table cell renderer.
There are two ways to associate a custom table cell renderer with a column. The first is to explicitly assign the renderer to the column; the example cited above demonstrates this method. The second is to associate the renderer with a type; this example demonstrates this method. The example installs a renderer for values of the type Color.
DefaultTableModel model = new DefaultTableModel() {
// This method returns the Class object of the first
// cell in specified column in the table model.
// Unless this method is overridden, all values are
// assumed to be the type Object.
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);
// Add data
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());
public class ColorTableCellRenderer extends JComponent implements TableCellRenderer {
// The current color to display
Color curColor;
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
// Set the color to paint
if (curColor instanceof Color) {
curColor = (Color)value;
} else {
// If color unknown, use table's background
curColor = table.getBackground();
}
return this;
}
// Paint current color
public void paint(Graphics g) {
g.setColor(curColor);
g.fillRect(0, 0, getWidth()-1, getHeight()-1);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -