• Post Reply Bookmark Topic Watch Topic
  • New Topic

Table header, how to make it wrap around  RSS feed

 
Sam Zheng
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Paul Stevens
Ranch Hand
Posts: 2823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you could do it by creating your String like this:
"Multi line\nstrings for\ntable"
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, Paul... labels (and table headers) strip out the "\n" character. But you can use HTML formatted Strings to do it :
 
Paul Stevens
Ranch Hand
Posts: 2823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!