Jtable:Is Nested header Possible

How to give nested header in java swing . I have defined the 4 main headers (type,source ,target ,default) wanted to have subheaders under each main header.
Example Code:
private String[] tableHeaders = new String[] {
               type,source ,target ,default};
private Vector<Vector<Object>> Vector = new Vector<Vector<Object>>();
private Vector<Object> headers = new Vector<Object>(
               Arrays.asList(tableHeaders));
private DefaultTableModel defaultTableModel = new DefaultTableModel(Vector,
               headers) {
          private static final long serialVersionUID = 1L;
          boolean[] columnEditables = new boolean[] { false, false, false, false };
          public boolean isCellEditable(int row, int column) {
               return columnEditables[column];
          public boolean isRowSelected(int row) {
               return true;
     };

I have worked on something similar. Here is one possible solution that you may want to try which is based on creating two tables - one main table and one inner table. Inner table is rendered as a column of the main table. You have to handle the table cell renderer and editor for the main table so that it can render inner table and allow normal table editing. I have added just one inner table in the code below but you can add more as per your requirement for showing them in other columns of the main table.
import java.awt.Component;     
import javax.swing.AbstractCellEditor; 
import javax.swing.JCheckBox;
import javax.swing.JFrame; 
import javax.swing.JScrollPane; 
import javax.swing.JTable; 
import javax.swing.table.DefaultTableCellRenderer;      
import javax.swing.table.DefaultTableModel; 
import javax.swing.table.TableCellEditor; 
import javax.swing.table.TableColumn; 
import javax.swing.table.TableColumnModel;
public class NestedJTableHeader extends JFrame { 
        private JTable mainTable; 
        private JTable innerTable; 
        private Object[][] tableList;        
        private String[] columnNames = {"A", "B", "C", "D", "E"}; 
        private Object[][] data = { 
                {"1", "2", "3", "4", new Boolean(false)}, 
                {"5", "6", "7", "8", new Boolean(true)}, 
                {"9", "10", "11", "12", new Boolean(false)}, 
                {"13", "14", "15", "16", new Boolean(true)}, 
                {"17", "18", "19", "20", new Boolean(false)} 
        private String[] names = {"Type", "Source", "Target", "Default"};
        public NestedJTableHeader(){            
            innerTable = new JTable(new DefaultTableModel (data, columnNames){
                    public Class<?> getColumnClass(int columnIndex) {
                         if(columnIndex==4)
                              return Boolean.class;
                         else
                              return super.getColumnClass(columnIndex);
            tableList = new Object[1][]; 
            tableList[0] = new Object[1]; 
            tableList[0][0] = innerTable; 
            mainTable = new JTable(new DefaultTableModel(tableList, names)); 
            TableColumn tc = mainTable.getColumnModel().getColumn(0); 
            tc.setCellRenderer(new CustomTableCellRenderer(innerTable)); 
            tc.setCellEditor(new CustomTableCellEditor(innerTable)); 
            tc = mainTable.getColumnModel().getColumn(1); 
            mainTable.setRowHeight(innerTable.getPreferredSize().height+innerTable.getTableHeader().getPreferredSize().height+4); 
            // Enable the ability to select a single cell  
            mainTable.setColumnSelectionAllowed(true);  
            mainTable.setRowSelectionAllowed(true);  
            this.getContentPane().add(new JScrollPane(mainTable)); 
            this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 
            this.pack();
            setSize(600,450);
            setVisible(true); 
        class CustomTableCellRenderer extends DefaultTableCellRenderer { 
            JTable table; 
            CustomTableCellRenderer(JTable table){ 
                this.table=table; 
                this.table.setOpaque(true); 
                this.table.setAlignmentY(JTable.LEFT_ALIGNMENT); 
            @Override 
            public Component getTableCellRendererComponent(JTable table, Object value, 
                    boolean isSelected, boolean hasFocus, int row, int column) { 
                this.table=(JTable)value; 
                return new JScrollPane(this.table);  
        class CustomTableCellEditor extends AbstractCellEditor implements TableCellEditor{ 
            JTable table; 
            CustomTableCellEditor(JTable table){ 
                this.table=table; 
                this.table.setOpaque(true); 
                this.table.setAlignmentY(JTable.LEFT_ALIGNMENT); 
            @Override 
            public Component getTableCellEditorComponent(JTable table, 
                    Object value, boolean isSelected, int row, int column) { 
                this.table=(JTable)value; 
                return new JScrollPane(this.table); 
            @Override 
            public Object getCellEditorValue() { 
                return this.table; 
         * @param args
        public static void main(String[] args) { 
            new NestedJTableHeader(); 
} Edited by: Nitin Khare on May 17, 2012 12:42 AM

Similar Messages

  • How to print jTable with custom header and footer....

    Hello all,
    I'm trying to print a jTable with custom header and footer.But
    jTable1.print(PrintMode,headerFormat,footerFormat,showPrintDialog,attr,interactive)
    does not allow multi line header and footer. I read in a chat that we can make custom header and footer and wrap the printable with that of the jTable. How can we do that..
    Here's the instruction on the chat...
    Shannon Hickey: While the default Header and Footer support in the JTable printing won't do exactly what you're looking for, there is a straight-forward approach. You can turn off the default header/footer and then wrap JTable's printable inside another Printable. This wrapper printable would then render your custom data, and then adjust the size given to the wrapped printable
    But how can i wrap the jTable's Printable with the custom header and footer.
    Thanks in advance,

    I also once hoped for an easy way to modify a table's header and footer, but found no way.
    Yet it is possible.

  • Jtable without column header

    Hi all,
    I have searched for jtable without column header... and if it´s possible how can I make?
    thanks

    Override JTable#configureEnclosingScrollPane() to do nothing or remove the table header manually ( jScrollPane.setColumnHeader(null) ) after you added the table to the scroll pane.

  • Print a JTable with several Header and Footers

    Hi everybody,
    my name is Lothar and I come from Germany. My english is not very well, but I hope you understand me an my problem.
    I want to print a JTable, but I want to print a header with several headers and footers.
    For example:
    h3. Header
    h5. 1. Subtitle
    h5. 2. Subtitle
    Table
    h5. 3. Subtitle
    h5. Footer
    But, I do not know how I can do that. Can anybody tell me, how I can solve my problem. Please, explain for a newbie because I have learned Java since two months ;)
    Here the code:
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import java.util.Date;
    import javax.swing.*;
    public class Beispiel extends JFrame implements ActionListener {
        private JTable table;
        public static void main(String[] args) {
            Beispiel tl = new Beispiel();
            tl.setVisible(true);
            tl.pack();
        public Beispiel() {
            setLayout(new BorderLayout());
            // DruckButton
            JButton print = new JButton("Print");
            add(print, BorderLayout.SOUTH);
            print.addActionListener(this);
            // Tabelle
            add(new JScrollPane(createTable()), BorderLayout.CENTER);
            // schlie&szlig;t das Frame
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public JTable createTable() {
            // titel
            String[] title = new String[] { "Datum", "Von", "Bis",
                    "Dauerinsgesamt", "Bemerkung" };
            // daten
            String[][] data = new String[][] { { "", "", "", "", "" },
            table = new JTable(data, title);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            return table;
        public void actionPerformed(ActionEvent e1) {
            MessageFormat header = new MessageFormat("Header");
            MessageFormat footer = new MessageFormat("Footer");
            try {
                table.print(JTable.PrintMode.FIT_WIDTH, header, footer);
            } catch (Exception e2) {
                System.err.format("Cannot print %s%n", e2.getMessage());
    }

    Nobody?
    Can nobody solve my problem?

  • JTable with Groupable Header

    Hi again, Im have problems with a JTable supporting Groupable Header
    check this code please:
    public class GroupableHeaderExample extends JFrame {
      GroupableHeaderExample() {
        super( "Groupable Header Example" );
        DefaultTableModel dm = new DefaultTableModel();
        dm.setDataVector(new Object[][]{
          {"119","foo","bar","ja","ko","zh"},
          {"911","bar","foo","en","fr","pt"}},
        new Object[]{"SNo.","1","2","Native","2","3"});
        JTable table = new JTable( dm ) {
          protected JTableHeader createDefaultTableHeader() {
         return new GroupableTableHeader(columnModel);
        TableColumnModel cm = table.getColumnModel();
        ColumnGroup g_name = new ColumnGroup("Name");
        g_name.add(cm.getColumn(1));
        g_name.add(cm.getColumn(2));
        ColumnGroup g_lang = new ColumnGroup("Language");
        g_lang.add(cm.getColumn(3));
        ColumnGroup g_other = new ColumnGroup("Others");
        g_other.add(cm.getColumn(4));
        g_other.add(cm.getColumn(5));
        g_lang.add(g_other);
        GroupableTableHeader header = (GroupableTableHeader)table.getTableHeader();
        header.addColumnGroup(g_name);
        header.addColumnGroup(g_lang);
        JScrollPane scroll = new JScrollPane( table );
        getContentPane().add( scroll );
        setSize( 400, 120 );  
      }it could be like this :
    * |-----------------------------------------------------|
    * |        |       Name      |         Language         |
    * |        |-----------------|--------------------------|
    * |  SNo.  |        |        |        |      Others     |
    * |        |   1    |    2   | Native |-----------------|
    * |        |        |        |        |   2    |   3    | 
    * |-----------------------------------------------------|
    * |        |        |        |        |        |        |
    */but it is looking like this:
    * |-----------------------------------------------------|
    * |  SNo.  |   1    |    2   | Native |   2    |   3    | 
    * |-----------------------------------------------------|
    * |        |        |        |        |        |        |
    */its look like correct, but i think the problem is in one of the clases called. what do you think? ... thanks
    Message was edited by:
    iTzAngel
    Message was edited by:
    iTzAngel

    STOP SPAMMING THE FORUMS!
    http://forum.java.sun.com/thread.jspa?threadID=5202466
    http://forum.java.sun.com/thread.jspa?threadID=5202411
    http://forum.java.sun.com/thread.jspa?threadID=5202439
    http://forum.java.sun.com/thread.jspa?threadID=5202369
    by the way, you are really spamming the forums

  • Whether JTable supports nesting of JButton or JCheckBox?

    Hi All,
    I need to show JButton or JCheckBoxes inside JTable. I tried extending from AbstractTableModel and overiden following method:
    public Object getValueAt(int row, int column)
    to return either JButton or JCheckBox, but while rendering the JTable it calls toString() method of the returned object i.e. either JButton or JCheckBox.
    Can any one pls guide me whether JTable supports nesting of JButton or JCheckBox? And if yes, How do I achieve the same.
    Pls reply at the earliest.
    Thanks,
    Sandesh

    Take a look at creating your own table cell renderer and table cell editor. Search for that on these forums, or better yet within Sun's Swing Java Tutorial. It can be done and it's not hard once you get the concept down. Note that JTable has a prepareRenderer method that returns a component to renderer, which can be any component you want and there are methods to easily assign a renderer and editor by column (or even more by cell, but that's a bit more complicated).

  • JTable with row header plus value extraction from headers

    Hi, I am trying to do the following:
    Short Version-
    1. Create a table that has both row and column headers
    2. Allow the user to mouse over any of these headers such that doing so will display an image I have produced on a panel. (I already know how to create the image and how to display it, I'm just not sure how to associate it with a particular row or column header)
    3. Make the row headers look as much as possible like the column headers.
    Slightly Longer Version-
    Column headers will be labled A-H (maximum) while row headers will be labled 1-12 (maximum). Either can be less, however, depending on user input. After the table has been realized, the user will move the mouse over say, header 'H' and when they do, a JPEG image will appear on another panel and a tooltip will appear above the cell showing a formula. This happens when either row or column headers are moused over.
    Currently, I am using the following code from the O'reilly Swing book as a baseline for experimentation but any help you can offer will be appreciated. I'm fairly new to the JTable world... :-(
    TableModel tm = new AbstractTableModel(){
                   String data[] = {"", "a", "b", "c", "d", "e"};
                   String headers [] = {"Row #", "Column1", "Column2", "Column3", "Column4", "Column5"};
                   public int getColumnCount(){ return data.length;}
                   public int getRowCount() { return 1000;}
                   public String getColumnName(int col){ return headers[col];}
                   public Object getValueAt(int row, int col){
                        return data[col] + row;
              //creates a column model for the main table. This model ignores the first
              //column added and sets a minimum width of 150 pixels for all others
              TableColumnModel cm = new DefaultTableColumnModel(){
                   boolean first = true;
                   public void addColumn(TableColumn tc){
                        if(first) {first = false; return;}
                        tc.setMinWidth(150);
                        super.addColumn(tc);
              //Creates a column model that will serve as the row header table. This model
              //picks a maxium width and stores only the first column
              TableColumnModel rowHeaderModel = new DefaultTableColumnModel(){
                   boolean first = true;
                   public void addColumn(TableColumn tc){
                        if(first) {
                             tc.setMaxWidth(tc.getPreferredWidth());
                             super.addColumn(tc);
                             first = false;
              JTable grid = new JTable(tm, cm);
              //set up the header column and hook it up to everything
              JTable headerColumn = new JTable(tm, rowHeaderModel);
              grid.createDefaultColumnsFromModel();
              headerColumn.createDefaultColumnsFromModel();
              //make sure the selection between the main table and the header stay in sync
              grid.setSelectionModel(headerColumn.getSelectionModel());
              headerColumn.setBorder(BorderFactory.createEtchedBorder());
              headerColumn.setBackground(Color.lightGray);
              headerColumn.setColumnSelectionAllowed(false);
              headerColumn.setCellSelectionEnabled(false);
              JViewport jv = new JViewport();
              jv.setView(headerColumn);
              jv.setPreferredSize(headerColumn.getMaximumSize());
              //to make the table scroll properly
              grid.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              //have to manually attach row headers but after that, the scroll pane
              //keeps them in sync
              JScrollPane jsp = new JScrollPane(grid);
              jsp.setRowHeader(jv);
              jsp.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, headerColumn.getTableHeader());
              gridPanel.add(jsp, BorderLayout.NORTH);

    There a number of nice examples on JTable: http://www.senun.com/Left/Programming/Java_old/Examples_swing/SwingExamples.html
    Hope you could find something suitable ...
    Regards,
    Anton.

  • Is nested li possible

    Is it possible to give nested ul, li in flash
    e.g.
    a.htmlText =
    "<ul><li>AAAA</li><li><li>BBBB</li></li></ul>";
    mine is not working, anybody with clue.
    Thanks in advance.

    No ordered bullets and nesting of bullets is not supported by
    Flash.
    You can use <tab> to align the text for nesting

  • Print jTable with a header and footer panel

    Hi Folks,
    I'm currently at a sticking point in a project I'm playing around with. I have a data set of around 300 objects that i'd like printed out in a table. Now, I've gotten the display part down without a hitch but printing the data as well as a header panel and footer panel has been eluding me. I'd basically like something like this...
    Name: some name Order date: some date
    Address: some address Shipped To: some address
    somewhere Some city, some state, etc
    in some city
    Date | Title | Etc | Etc | Etc
    date1 title1 5 $3.00 $15.00
    date1 title1 5 $3.00 $15.00
    date2 title1 5 $3.00 $15.00
    date2 title1 5 $3.00 $15.00
    Total purchases: $60.00
    Total Items: 20
    # of Orders: 2
    Am I barking up the wrong tree by making the first and third sections panels and the second section a table? If not, how the heck do I accomplish this? Most of the time the table has been multiple pages as well - I only need section one on the first page and section three on the last page, but whatever is easiest really.
    My current approach has been basically to make a custom printables, print the first section, figure out how high it was, print the second section and hope for the best, but the third would never show up because it'd never go over two pages.
    Any help would be very much appreciated.
    Thanks,
    Stephen
    Edited by: stephenliberty on May 7, 2009 9:11 AM - more specific subject

    I suppose as a quick update, this is as far as I've gotten and will likely get-
    public class PrintForm extends JFrame implements Printable{
        JComponent headerPanelForPrint;
        JComponent footerPanelForPrint;
        JTable dataTableForPrint;
        public void setPieces(JComponent header, JTable table, JComponent footer){
            this.headerPanelForPrint = header;
            this.footerPanelForPrint = footer;
            this.dataTableForPrint = table;
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
            graphics.translate((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY());
            TableFormat tableFormat;
            if(pageIndex>0){
                tableFormat = new TableFormat(0, footerPanelForPrint.getHeight());
            } else {
                headerPanelForPrint.printAll(graphics);
                tableFormat = new TableFormat(headerPanelForPrint.getHeight(), footerPanelForPrint.getHeight());
            MessageFormat footer = new MessageFormat("Page - {0}");
            Printable table = dataTableForPrint.getPrintable(PrintMode.FIT_WIDTH, null, footer);
            int printme = table.print(graphics, tableFormat, pageIndex);
            if(printme == table.NO_SUCH_PAGE){ return table.NO_SUCH_PAGE; }
            return Printable.PAGE_EXISTS;
    class TableFormat extends PageFormat {
        double footerHeight;
        double headerHeight;
        public TableFormat(double headerHeight, double footerHeight){
            this.headerHeight = headerHeight;
            this.footerHeight = footerHeight;
        @Override
        public double getImageableHeight() {
            return super.getImageableHeight() - ( this.footerHeight + this.headerHeight );
        @Override
        public double getHeight() {
            return super.getImageableHeight() - ( this.footerHeight + this.headerHeight);
        @Override
        public double getImageableX() {
            return 0;
        @Override
        public double getImageableY() {
            return this.headerHeight;
    }It works very well with just a header and the table, but I still have not been able to get a footer to show up in the appropriate spot or (preferably) on the last page.
    Edited by: stephenliberty on May 8, 2009 12:29 PM

  • JTable: Resizable Row Header

    Hi,
    Did anyone implement a row header class for JTable that allows to resize rows (the height of rows) like JTableHeader does for columns?

    Take a look at the link shown below:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=252175
    ;o)
    V.V.

  • JTable multi line header behaves strangely

    Hello,
    I'm trying to use html-tags in my JTable headers. For some reasons only the first column-name has any effect on the header height. If the other columns have more lines than the first column, they are cut off.
    Is there a solution to this problem?

    I extended the JTable and overrode the addColumn method:
       @Override
       public void addColumn(TableColumn column) {
          super.addColumn(column);
          if (column!= null && getTableHeader() != null
                && getTableHeader().getDefaultRenderer() != null) {
             column.setHeaderRenderer(getTableHeader().getDefaultRenderer());
       }That seemed to work well, but perhaps there are more elegant solutions?

  • Print Jtable with multiline header?

    i want to print jtable with multi-lines header and footer
    using the print function that takes MessageFormat as header and footer
    i used MessageFormat header = new MessageFormat("hello\r\nworld");and i used '\n' only
    but it was printed all in the same line
    thnx in advance

    You can try something on the below lines. Set your custom renderer for the tableheader.
    public class MultiLineHeaderRenderer extends DefaultTableCellRenderer{
            public Component getTableCellRendererComponent(JTable table, Object value,
                             boolean isSelected, boolean hasFocus, int row, int column) {
                         JLabel label = (JLabel) super.getTableCellRendererComponent( table,  value,
                              isSelected,  hasFocus,  row,  column);
                        label.setText("<html>a<br>b</html>");
                        return label;
        }Not the best way to do it. And might need to some modifications too to set the font position etc.

  • Simple XML (XPATH) 'nested loop' possible?

    What's the best way to output the entries of an XML file with
    the following structure as a nested list (actually it needs to
    become a form where all entries can be checked).
    I can output each level (see code) but it seems not to be
    possible to nest the for-loops.
    Any hints if it's possible with XPath directly or do I need
    to save the result of one loop to output within the other or would
    it even be better to make a query out of the XML result?

    Thanks, great!
    I tried it somwhere along this before but it didn't work
    then. I propably just forgot to put the pound signes to the correct
    place or something ;-)
    But yes, your solution is exactly what I was looking for!
    Thank you

  • JTable - Groupable/Multiline Header

    Hi Everybody,
    I found this code to create a groupable/multiline header for a JTable. It seems to be working fine with JDK 1.1 and we are using 1.4 now. I keep getting 2 errors with the GroupableTableHeaderUI class and has been busy the whole weekend trying to fix it, with no success. Can someone please help? Thanks. Here is the code:
    * |-----------------------------------------------------|
    * | | Name | Language |
    * | |-----------------|--------------------------|
    * | SNo. | | | | Others |
    * | | 1 | 2 | Native |-----------------|
    * | | | | | 2 | 3 |
    * |-----------------------------------------------------|
    * | | | | | | |
    package tableheader;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import swing.table.*;
    public class GroupableHeaderExample extends JFrame {
    GroupableHeaderExample() {
    super( "Groupable Header Example" );
    DefaultTableModel dm = new DefaultTableModel();
    dm.setDataVector(new Object[][]{
    {"119","foo","bar","ja","ko","zh"},
    {"911","bar","foo","en","fr","pt"}},
    new Object[]{"SNo.","1","2","Native","2","3"});
    JTable table = new JTable( dm ) {
    protected JTableHeader createDefaultTableHeader() {
         return new GroupableTableHeader(columnModel);
    TableColumnModel cm = table.getColumnModel();
    ColumnGroup g_name = new ColumnGroup("Name");
    g_name.add(cm.getColumn(1));
    g_name.add(cm.getColumn(2));
    ColumnGroup g_lang = new ColumnGroup("Language");
    g_lang.add(cm.getColumn(3));
    ColumnGroup g_other = new ColumnGroup("Others");
    g_other.add(cm.getColumn(4));
    g_other.add(cm.getColumn(5));
    g_lang.add(g_other);
    GroupableTableHeader header = (GroupableTableHeader)table.getTableHeader();
    header.addColumnGroup(g_name);
    header.addColumnGroup(g_lang);
    JScrollPane scroll = new JScrollPane( table );
    getContentPane().add( scroll );
    setSize( 400, 120 );
    public static void main(String[] args) {
    GroupableHeaderExample frame = new GroupableHeaderExample();
    frame.addWindowListener( new WindowAdapter() {
    public void windowClosing( WindowEvent e ) {
         System.exit(0);
    frame.setVisible(true);
    package swing.table;
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class GroupableTableHeader extends JTableHeader {
    private static final String uiClassID = "GroupableTableHeaderUI";
    protected Vector columnGroups = null;
    public GroupableTableHeader(TableColumnModel model) {
    super(model);
    setUI(new GroupableTableHeaderUI());
    setReorderingAllowed(false);
    public void setReorderingAllowed(boolean b) {
    reorderingAllowed = false;
    public void addColumnGroup(ColumnGroup g) {
    if (columnGroups == null) {
    columnGroups = new Vector();
    columnGroups.addElement(g);
    public Enumeration getColumnGroups(TableColumn col) {
    if (columnGroups == null) return null;
    Enumeration enum = columnGroups.elements();
    while (enum.hasMoreElements()) {
    ColumnGroup cGroup = (ColumnGroup)enum.nextElement();
    Vector v_ret = (Vector)cGroup.getColumnGroups(col,new Vector());
    if (v_ret != null) {
         return v_ret.elements();
    return null;
    public void setColumnMargin() {
    if (columnGroups == null) return;
    int columnMargin = getColumnModel().getColumnMargin();
    Enumeration enum = columnGroups.elements();
    while (enum.hasMoreElements()) {
    ColumnGroup cGroup = (ColumnGroup)enum.nextElement();
    cGroup.setColumnMargin(columnMargin);
    package swing.table;
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.plaf.basic.*;
    public class GroupableTableHeaderUI extends BasicTableHeaderUI {
    public void paint(Graphics g, JComponent c) {
    Rectangle clipBounds = g.getClipBounds();
    if (header.getColumnModel() == null) return;
    ((GroupableTableHeader)header).setColumnMargin();
    int column = 0;
    Dimension size = header.getSize();
    Rectangle cellRect = new Rectangle(0, 0, size.width, size.height);
    Hashtable h = new Hashtable();
    int columnMargin = header.getColumnModel().getColumnMargin();
    Enumeration enumeration = header.getColumnModel().getColumns();
    while (enumeration.hasMoreElements()) {
    cellRect.height = size.height;
    cellRect.y = 0;
    TableColumn aColumn = (TableColumn)enumeration.nextElement();
    Enumeration cGroups = ((GroupableTableHeader)header).getColumnGroups(aColumn);
    if (cGroups != null) {
    int groupHeight = 0;
    while (cGroups.hasMoreElements()) {
    ColumnGroup cGroup = (ColumnGroup)cGroups.nextElement();
    Rectangle groupRect = (Rectangle)h.get(cGroup);
    if (groupRect == null) {
    groupRect = new Rectangle(cellRect);
    Dimension d = cGroup.getSize(header.getTable());
    groupRect.width = d.width;
    groupRect.height = d.height;
    h.put(cGroup, groupRect);
    paintCell(g, groupRect, cGroup);
    groupHeight += groupRect.height;
    cellRect.height = size.height - groupHeight;
    cellRect.y = groupHeight;
    cellRect.width = aColumn.getWidth() + columnMargin;
    if (cellRect.intersects(clipBounds)) {
    paintCell(g, cellRect, column);
    cellRect.x += cellRect.width;
    column++;
    private void paintCell(Graphics g, Rectangle cellRect, int columnIndex) {
    TableColumn aColumn = header.getColumnModel().getColumn(columnIndex);
    TableCellRenderer renderer = aColumn.getHeaderRenderer();
    Component component = renderer.getTableCellRendererComponent(
    header.getTable(), aColumn.getHeaderValue(),false, false, -1, columnIndex);
    rendererPane.add(component);
    rendererPane.paintComponent(g, component, header, cellRect.x, cellRect.y,
                        cellRect.width, cellRect.height, true);
    private void paintCell(Graphics g, Rectangle cellRect,ColumnGroup cGroup) {
    TableCellRenderer renderer = cGroup.getHeaderRenderer();
    Component component = renderer.getTableCellRendererComponent(
    header.getTable(), cGroup.getHeaderValue(),false, false, -1, -1);
    rendererPane.add(component);
    rendererPane.paintComponent(g, component, header, cellRect.x, cellRect.y,
                        cellRect.width, cellRect.height, true);
    private int getHeaderHeight() {
    int height = 0;
    TableColumnModel columnModel = header.getColumnModel();
    for(int column = 0; column < columnModel.getColumnCount(); column++) {
    TableColumn aColumn = columnModel.getColumn(column);
    TableCellRenderer renderer = aColumn.getHeaderRenderer();
    Component comp = renderer.getTableCellRendererComponent(
    header.getTable(), aColumn.getHeaderValue(), false, false,-1, column);
    int cHeight = comp.getPreferredSize().height;
    Enumeration enum = ((GroupableTableHeader)header).getColumnGroups(aColumn);
    if (enum != null) {
    while (enum.hasMoreElements()) {
    ColumnGroup cGroup = (ColumnGroup)enum.nextElement();
    cHeight += cGroup.getSize(header.getTable()).height;
    height = Math.max(height, cHeight);
    return height;
    private Dimension createHeaderSize(long width) {
    TableColumnModel columnModel = header.getColumnModel();
    width += columnModel.getColumnMargin() * columnModel.getColumnCount();
    if (width > Integer.MAX_VALUE) {
    width = Integer.MAX_VALUE;
    return new Dimension((int)width, getHeaderHeight());
    public Dimension getPreferredSize(JComponent c) {
    long width = 0;
    Enumeration enumeration = header.getColumnModel().getColumns();
    while (enumeration.hasMoreElements()) {
    TableColumn aColumn = (TableColumn)enumeration.nextElement();
    width = width + aColumn.getPreferredWidth();
    return createHeaderSize(width);
    package swing.table;
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class ColumnGroup {
    protected TableCellRenderer renderer;
    protected Vector v;
    protected String text;
    protected int margin=0;
    public ColumnGroup(String text) {
    this(null,text);
    public ColumnGroup(TableCellRenderer renderer,String text) {
    if (renderer == null) {
    this.renderer = new DefaultTableCellRenderer() {
         public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
         JTableHeader header = table.getTableHeader();
         if (header != null) {
         setForeground(header.getForeground());
         setBackground(header.getBackground());
         setFont(header.getFont());
    setHorizontalAlignment(JLabel.CENTER);
    setText((value == null) ? "" : value.toString());
         setBorder(UIManager.getBorder("TableHeader.cellBorder"));
         return this;
    } else {
    this.renderer = renderer;
    this.text = text;
    v = new Vector();
    * @param obj TableColumn or ColumnGroup
    public void add(Object obj) {
    if (obj == null) { return; }
    v.addElement(obj);
    * @param c TableColumn
    * @param v ColumnGroups
    public Vector getColumnGroups(TableColumn c, Vector g) {
    g.addElement(this);
    if (v.contains(c)) return g;
    Enumeration enum = v.elements();
    while (enum.hasMoreElements()) {
    Object obj = enum.nextElement();
    if (obj instanceof ColumnGroup) {
    Vector groups =
    (Vector)((ColumnGroup)obj).getColumnGroups(c,(Vector)g.clone());
    if (groups != null) return groups;
    return null;
    public TableCellRenderer getHeaderRenderer() {
    return renderer;
    public void setHeaderRenderer(TableCellRenderer renderer) {
    if (renderer != null) {
    this.renderer = renderer;
    public Object getHeaderValue() {
    return text;
    public Dimension getSize(JTable table) {
    Component comp = renderer.getTableCellRendererComponent(
    table, getHeaderValue(), false, false,-1, -1);
    int height = comp.getPreferredSize().height;
    int width = 0;
    Enumeration enum = v.elements();
    while (enum.hasMoreElements()) {
    Object obj = enum.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);
    public void setColumnMargin(int margin) {
    this.margin = margin;
    Enumeration enum = v.elements();
    while (enum.hasMoreElements()) {
    Object obj = enum.nextElement();
    if (obj instanceof ColumnGroup) {
    ((ColumnGroup)obj).setColumnMargin(margin);

    in GroupableTableHeaderUI class replace "aColumn.getHeaderRenderer();" by "header.getDefaultRenderer ();" and try again..
    this should solve ur problem ..
    Indranil

  • JTabbedPane, switch of auto resizing of the tab header possible?

    Hi,
    Is it possible to prevent the tab header from auto resizing?
    In this code the tab "Page 1" fills the whole row at start up, but I would like to prevent it from taking more space than needed.
    import java.awt.*;
    import javax.swing.*;
    class TabbedPaneExample
            extends     JFrame
        private        JTabbedPane tabbedPane;
        private        JPanel        panel1;
        private        JPanel        panel2;
        private        JPanel        panel3;
        public TabbedPaneExample()
            // NOTE: to reduce the amount of code in this example, it uses
            // panels with a NULL layout.  This is NOT suitable for
            // production code since it may not display correctly for
            // a look-and-feel.
            setTitle( "Tabbed Pane Application" );
            setSize( 140, 200 );
            setBackground( Color.gray );
            JPanel topPanel = new JPanel();
            topPanel.setLayout( new BorderLayout() );
            getContentPane().add( topPanel );
            // Create the tab pages
            createPage1();
            createPage2();
            createPage3();
            // Create a tabbed pane
            tabbedPane = new JTabbedPane();
            tabbedPane.addTab( "Page 1", panel1 );
            tabbedPane.addTab( "Page 2", panel2 );
            tabbedPane.addTab( "Page 3", panel3 );
            topPanel.add( tabbedPane, BorderLayout.CENTER );
        public void createPage1()
            panel1 = new JPanel();
            panel1.setLayout( null );
        public void createPage2()
            panel2 = new JPanel();
            panel2.setLayout( new BorderLayout() );
        public void createPage3()
            panel3 = new JPanel();
            panel3.setLayout( new GridLayout( 3, 2 ) );
        // Main method to get things started
        public static void main( String[] args )
            // Create an instance of the test application
            TabbedPaneExample mainFrame    = new TabbedPaneExample();
            mainFrame.setVisible( true );
    }Edited by: user6102378 on 2010-okt-07 06:51

    Unfortunately, the answer seems to be "no" - looks like the exact behaviour is even different across different LAFs. Nothing short of re-writing the layout code in the xxTabbedPaneUI will help.
    Just curious: how comes that we have so many tabbedPane related questions recently?
    Cheers
    Jeanette

Maybe you are looking for