JTable header text wrapping for multiline header (custom TableCellRenderer)

后端 未结 3 2118
野趣味
野趣味 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:26

    This here also uses JTextArea and also resizes the header height when the table is resized. The key to the correct calculation of the table header height is setSize(width, getPreferredSize().height);

    class MultiLineTableHeaderRenderer extends JTextArea implements TableCellRenderer
    {
      public MultiLineTableHeaderRenderer() {
        setEditable(false);
        setLineWrap(true);
        setOpaque(false);
        setFocusable(false);
        setWrapStyleWord(true);
        LookAndFeel.installBorder(this, "TableHeader.cellBorder");
      }
    
      @Override
      public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        int width = table.getColumnModel().getColumn(column).getWidth();
        setText((String)value);
        setSize(width, getPreferredSize().height);
        return this;
      }
    }
    

提交回复
热议问题