How to wrap lines in a jtable cell?

前端 未结 8 1079
面向向阳花
面向向阳花 2020-11-29 09:11

I\'m trying to implement a custom TableRenderer as described in this tutorial. I\'d like to have the renderer line-wrap each text that is to long for the given cell. The i

8条回答
  •  我在风中等你
    2020-11-29 09:46

    I stumbled in this same problem, and I needed to modify a little the code that it was written here, so I attach my own version:

    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.JTextArea;
    import javax.swing.table.TableCellRenderer;
    
     public class LineWrapCellRenderer extends JTextArea implements TableCellRenderer {
    
        @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
            int row, int column) {
        this.setText((String) value);
        this.setWrapStyleWord(true);
        this.setLineWrap(true);
    
        int fontHeight = this.getFontMetrics(this.getFont()).getHeight();
        int textLength = this.getText().length();
        int lines = textLength / this.getColumnWidth();
        if (lines == 0) {
            lines = 1;
        }
    
        int height = fontHeight * lines;
        table.setRowHeight(row, height);
    
        return this;
     }
    
    }
    

提交回复
热议问题