Multiline JTable
cell can make using a customized TableCellRenderer
easily. Use following steps to create the TableCellRenderer
.
Step 1: Create TableCellRenderer
Following code shows to create a multi-line TableCellRenderer
for String[]
values. It's possible to change the String[]
into a Vector
or an other Collection
type
public class MultiLineTableCellRenderer extends JList<String> implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
//make multi line where the cell value is String[]
if (value instanceof String[]) {
setListData((String[]) value);
}
//cell backgroud color when selected
if (isSelected) {
setBackground(UIManager.getColor("Table.selectionBackground"));
} else {
setBackground(UIManager.getColor("Table.background"));
}
return this;
}
}
Step 2: Set TableCellRenderer
into the JTable
MultiLineTableCellRenderer renderer = new MultiLineTableCellRenderer();
//set TableCellRenderer into a specified JTable column class
table.setDefaultRenderer(String[].class, renderer);
//or, set TableCellRenderer into a specified JTable column
table.getColumnModel().getColumn(columnIndex).setCellRenderer(renderer);
This is my tested screenshot:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…