Auto adjust the height of rows in a JTable
The only way to know the row height for sure is to render each cell to determine the rendered height. After your table is populated with data you can do:
private void updateRowHeights()
{
for (int row = 0; row < table.getRowCount(); row++)
{
int rowHeight = table.getRowHeight();
for (int column = 0; column < table.getColumnCount(); column++)
{
Component comp = table.prepareRenderer(table.getCellRenderer(row, column), row, column);
rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
}
table.setRowHeight(row, rowHeight);
}
}
If only the first column can contain multiple line you can optimize the above code for that column only.
How to set the RowHeight dynamically in a JTable
There are several issues when using a JTextArea as rendering component (and most if not all of them already explained in several QA's on this site). Trying to sum them up:
Adjust individual row height to the size requirements of the rendering component
Basically, the way to go is to loop through the cells as needed, then
- configure its renderer with the data
- ask the rendering component for its preferred size
- set the table row height to the pref height
The updateRowHeight method in the OP's edited question is just fine.
JTextArea's calculation of its preferredSize
to get a reasonable sizing hint for one dimension, it needs to be "seeded" with some reasonable size in the other dimension. That is if we want the height it needs a width, and that must be done in each call. In the context of a table, a reasonable width is the current column width:
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
... // configure visuals
setText((String) value);
setSize(table.getColumnModel().getColumn(column).getWidth(),
Short.MAX_VALUE);
return this;
}// getTableCellRendererComponent
Dynamic adjustment of the height
The row height it fully determined in some steady state of the table/column/model. So you set it (call updateRowHeight) once after the initialization is completed and whenever any of the state it depends on is changed.
// TableModelListener
@Override
public void tableChanged(TableModelEvent e) {
updateRowHeights();
}
// TableColumnModelListener
@Override
public void columnMarginChanged(ChangeEvent e) {
updateRowHeights();
}
Note
As a general rule, all parameters in the getXXRendererComponent are strictly read-only, implementations must not change any state of the caller. Updating the rowHeight from within the renderer is wrong.
Setting the height of a row in a JTable in java
Not sure what is the intention of leaving the first row at index 0 empty. Rows in JTable
run from index 0. It is best if you could post a complete example (ie SSCCE) that demonstrates the issues. Compare to this simple example that works OK:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class DemoTable {
private static void createAndShowGUI() {
JFrame frame = new JFrame("DemoTable");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new Object[] {
"Column 1", "Column 2", "Column 3" });
JTable table = new JTable(model);
for (int count = 0; count < 3; count++){
model.insertRow(count, new Object[] { count, "name", "age"});
}
table.setRowHeight(1, 30);
frame.add(new JScrollPane(table));
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
JTable change the row height dynamically
table.setRowHeight(...);
If you need more help post your SSCCE.
Proper way setting the column width and row height of JTable
You can use JTable#setRowHeight(int, int)
to set the height of individual rows and you will need to use the ColumnModel
and obtain a reference to the TableColumn
in order to change it's size.
Remember though, the size of a column may be affected by the autoResizeMode
How to change JTable row height globally?
Basically, there is nothing by intention. The relevant code-comment in BasicTableUI:
// JTable's original row height is 16. To correctly display the
// contents on Linux we should have set it to 18, Windows 19 and
// Solaris 20. As these values vary so much it's too hard to
// be backward compatable and try to update the row height, we're
// therefor NOT going to adjust the row height based on font. If the
// developer changes the font, it's there responsability to update
// the row height.
On the bright side, some LAFs like f.i. Nimbus respect a ui property for rowHeight:
UIManager.put("Table.font", new FontUIResource(new Font("SansSerif", Font.PLAIN, 28)));
// here simply the font height, need to do better
int height = 28;
UIManager.put("Table.rowHeight", height);
Related Topics
When Does Java's Thread.Sleep Throw Interruptedexception
Eclipse/Maven Error: "No Compiler Is Provided in This Environment"
Sonar Violation: Security - Array Is Stored Directly
How to Create New Xml File from Existing Database in Postgresql Database Using Java
Getting the Array Length of a 2D Array in Java
Looking for Java Spell Checker Library
Count Occurrences of Words in Arraylist
How to Use the Unsigned Integer in Java 8 and Java 9
How to Find Out If "Debug Mode" Is Enabled
Can't Rid of 'T' in Localdatetime
In Java, How to Call a Base Class's Method from the Overriding Method in a Derived Class
How to Hide Cursor in a Swing Application
Java Library to Compare Image Similarity
Cannot Instantiate the Type List<Product>
Custom Objectmapper with Jersey 2.2 and Jackson 2.1
How to Convert Timestamp to Date in Java
Intellij - Convert a Java Project/Module into a Maven Project/Module