JTable header text wrapping for multiline header (custom TableCellRenderer)

后端 未结 3 2120
野趣味
野趣味 2021-01-13 08:42

How can I obtain a multiline JTable header where the header column correctly enlarges to fit some text and then wraps to a new line?

Something like shown below:

3条回答
  •  心在旅途
    2021-01-13 09:30

    you need a Conponent that is able to wordwrap its content like JTextArea. I changed the cell renderer from your SSCCE so that is works initially, but it has a nasty resize behavior.

     class MultiLineHeaderRenderer extends JTextArea implements TableCellRenderer {
        public MultiLineHeaderRenderer()
        {
            setAlignmentY(JLabel.CENTER);
            setLineWrap(true);
            setWrapStyleWord(true);
            setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(Color.BLACK),
                    BorderFactory.createEmptyBorder(3,3,3,3)
                    ));
    
        }
    
        @Override
        public Component getTableCellRendererComponent(JTable table,
                Object value,
                boolean isSelected,
                boolean hasFocus,
                int row,
                int column) {
            setFont(table.getFont());
            String str = (value == null) ? "" : value.toString();
            setText(str);
            int columnWidth= getColumnWidth();
            setRows(str.length()/columnWidth);
            return this;
        }
    }
    

提交回复
热议问题