Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing - Multiple column headers in a JTable?

Tags:

java

swing

jtable

Is there any way to create multiple column headers in a JTable? I mean, normally there is only one row, but I need two of them with the same format (headerlike), and combine some cells of one of those headers.

I need something like this:

Header0 |          Header123          | Header4
Header0 | Header1 | Header2 | Header3 | Header4

Is there any way?

like image 778
Juan Diego Avatar asked Jul 23 '10 16:07

Juan Diego


1 Answers

Nick Meyer thanks for kindly reply, while the content in your address is a little out of date. i run it with jre 1.7 and it didn't works as expected but it can be altered to work correct. the alter i made are as follow

/*
* add these code in GroupableTableHeader
*/

  public void updateUI(){
//      setUI(this.getUI());

      TableCellRenderer renderer = getDefaultRenderer();
      if (renderer instanceof Component) {
          SwingUtilities.updateComponentTreeUI((Component)renderer);
      }
  }

/*
* add these code in GroupableTableHeaderUI in 2 places, you must know where
*/
      if (renderer == null) {
          renderer = header.getDefaultRenderer();
      }

/*
* change the getSize method in ColumnGroup 
*/

  public Dimension getSize(JTable table) {
    Component comp = renderer.getTableCellRendererComponent(
        table, getHeaderValue(), false, false,-1, -1);
    int height = comp.getPreferredSize().height; 
    int width  = 0;
    Enumeration en = v.elements();
    while (en.hasMoreElements()) {
      Object obj = en.nextElement();
      if (obj instanceof TableColumn) {
        TableColumn aColumn = (TableColumn)obj;
        width += aColumn.getWidth();
//        width += margin;
      } else {
        width += ((ColumnGroup)obj).getSize(table).width;
      }
    }
    return new Dimension(width, height);
  }

and the finally results. enter image description here

like image 93
SalutonMondo Avatar answered Oct 05 '22 02:10

SalutonMondo