I would like to create a JTable
like the below picture:
Which java
class will be used and possibly how?
length(); int lines = textLength / this. getColumns() +1;//+1, cause we need at least 1 row. int height = fontHeight * lines; table. setRowHeight(row, height);
We can change the background and foreground color for each column of a JTable by customizing the DefaultTableCellRenderer class and it has only one method getTableCellRendererComponent() to implement it.
You can use the getRowCount() method: Returns the number of rows that can be shown in the JTable , given unlimited space. If a RowSorter with a filter has been specified, the number of rows returned may differ from that of the underlying TableModel .
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:
basically you can put any type of JComponents
to the JTable
cell, depends of if is contents editable, thats talking me about follows
JTable
with one TableColumn
without TableHeader
JPanel
(GridBagLayout
) with JLabels
or JTextFields
JList
This will not work if you use a DefaultTableModel
. You have to use a custom model for your table that extends AbstractTableModel
and have to override the method getColumnClass()
, along with other abstract methods.
You will also set your table row height as mentioned in a comment above.
The official documentation from Oracle clarifies this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With