Table header, how to make it wrap around

Sam Zheng

Ranch Hand

Posts: 61

posted 14 years ago

I have a table with quite long header for each column, such as "Measured Distance (ft)", "Calculated Coefficient", etc. When I display the table, it only shows part of the header, such as "Measured..". How can I make it wrap around into the second line so that it shows something like: Measured Distance (ft) or even Measured Distance (ft) Please help! Sam

Vikalp Setya

Greenhorn

Posts: 18

posted 14 years ago

Hi, You will have to write a custom renderer for the table header that wraps its text.

1) Get the JTableHeader component from the table 2) set renderer for that component to an object of renderer class that you will be writing something like following: header.setDefaultRenderer(new MyHeaderRenderer())); import java.awt.*; import javax.swing.*; import javax.swing.table.*; public class MyHeaderRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {JTextArea area = new JTextArea(); area.setEditable(false); area.setLineWrap(true); area.setText(value.toString()); return area; } } You got to make this textarea look like a JLabel you can do it by setting the foreground color and the background color and disabling the text selection and so on.

Regards,<br />vikalps

Paul Stevens

Ranch Hand

Posts: 2823

posted 14 years ago

Or you could do it by creating your String like this: "Multi line\nstrings for\ntable"

Originally posted by Nathan Pruett: Sorry, Paul... labels (and table headers) strip out the "\n" character. But you can use HTML formatted Strings to do it :

I wasn't paying attention. I do have a renderer for where I use that.

Sam Zheng

Ranch Hand

Posts: 61

posted 14 years ago

The suggestion on using table header renderer is good except it wraps the text based on letter instead of word, i.e., it wraps the text like measured d istance How can I make it wraps text based on word such as measured distance BTW, the use of HTML tag is great. It solves my problem. But I am still curious about using the renderer. Thanks! Sam.