How to set the RowHeight dynamically in a JTable

后端 未结 5 1433
感动是毒
感动是毒 2020-12-09 20:39

I want to put a String in a JTable that is longer than the given cell-width. How can I set the rowHeight dynamically so that I can read the whole S

5条回答
  •  误落风尘
    2020-12-09 21:16

    I find it simplest to adjust the row height from inside the component renderer, like this:

    public class RowHeightCellRenderer extends JTextArea implements TableCellRenderer
    {
        public Component getTableCellRendererComponent(JTable table, Object 
                value, boolean isSelected, boolean hasFocus,
                int row, int column) {
    
            setText(value.toString());
    
            // Set the component width to match the width of its table cell
            // and make the height arbitrarily large to accomodate all the contents
            setSize(table.getColumnModel().getColumn(column).getWidth(), Short.MAX_VALUE);
    
            // Now get the fitted height for the given width
            int rowHeight = this.getPreferredSize().height;
    
            // Get the current table row height
            int actualRowHeight = table.getRowHeight(row);
    
            // Set table row height to fitted height.
            // Important to check if this has been done already
            // to prevent a never-ending loop.
            if (rowHeight != actualRowHeight) {
               table.setRowHeight(row, rowHeight);
            }
    
            return this;
        }
    }
    

    This will also work for a renderer which returns a JTextPane.

提交回复
热议问题