tags:

views:

618

answers:

1

Hi, I use JTable GUI component with NetBeans.

  • I want to create multi-line headers

  • I am able to this, when I create custom renderer for table headers

  • BUT I don't want to, because I like default one (I use it everywhere else in program).

  • So the problem is : How to make header heigher?

My code :

String headers[] = new String[3];
    headers[0] = "Header1";
    headers[1] = "Header2";
    headers[2] = "<html><center>Long<br>Centered</br></center></html>";
    DefaultTableModel dtm = new DefaultTableModel();
    dtm.setColumnIdentifiers(headers);
    dtm.setRowCount(5);
    jTable1.setModel(dtm);
    jTable1.getTableHeader().setPreferredSize(new Dimension(jTable1.getColumnModel().getTotalColumnWidth(),32));

alt text

+1  A: 

Try the following:

table.getTableHeader().setPreferredSize(
      new Dimension(table.getColumnModel().getTotalColumnWidth(), 32));

This will change the size of the header:

alt text

To center the text, you can use the <center>-tag:

headers[2] = "<html><center>Long Centered<br>Header";

alt text

EDIT:

The alignment is set by your LookAndFeel. WindowsTableHeaderUI for example explicitly calls

setHorizontalAlignment(LEADING);

The easiest way to solve this is:

(JLabel)table.getTableHeader().getDefaultRenderer())
      .setHorizontalAlignment(SwingConstants.CENTER);

Note that this change is lost when you change your LookAndFeel afterwards.

Peter Lang
Great, thanx that's what I need.However, I am now having quite trouble center text in header ...Is there any chance you know how to?
miso
html <center> tag wont help ...SwingConstants.CENTER would, but I would againg need to create own renderer for headers :/
miso
I tried `center` and it worked: `"<html><center>Long<br>Header</br></html>"`. Have you tried like this?
Peter Lang
headers[0] = "<html>Monday<br>"+week[0]+"</br></html>";Does not work for me :/My headers are resizable btw
miso
What does not work with it?
Peter Lang
I edited original post, please look
miso
Peter you helped me once again, I am thankful :)It is correct as you suggest ((JLabel)table.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(SwingConstants.CENTER); solves it
miso