0

How can I make it so that my table headers will be rendered over multiple lines if it consists of multiple words?

This is what I have so far:

public class MultiLineHeaderRenderer extends JList implements TableCellRenderer
{

    @Override
    public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        setFont(table.getFont());
        String str = (value == null) ? "" : value.toString();
        BufferedReader br = new BufferedReader(new StringReader(str));
        String line = "";
        int character;
        Vector v = new Vector();
        try 
        {
            character = br.read();
            while (character != -1) 
            {
                System.out.println("character = " + (char) character);
                System.out.println("character = " + character);
                line = line + String.valueOf((char) character);
                if((char) character == ' ')
                {
                    System.out.println("hello");
                    v.addElement(line);
                    line = "";
                }
                character = br.read();
            }
            v.addElement(line);
        }
        } catch (IOException ex) {
          ex.printStackTrace();
        }
        setListData(v);
        return this;
    }
}

However this doesn't show anything at all.

If instead of the try block I do:

        v.addElement("line1");
        v.addElement("line2");

It displays both lines as expected (albeit it's ugly, it just has a white background, no lines to separate columns, not center justified, etc.)

What am I doing wrong? How do I implement multi line table headers?

Edit: I've updated the try block, it's now giving me just the first word and nothing else.

Aequitas
  • 2,205
  • 1
  • 25
  • 51
  • This could help: http://www.java2s.com/Code/Java/Swing-Components/MultiLineHeaderExample.htm – chris Jul 15 '15 at 04:46
  • @Chris that's what I worked from, I changed it though because they put it on the same line – Aequitas Jul 15 '15 at 04:50
  • @Aequitas are you looking to have this behaviour when columns are resized? or by default you want to display them in multiple rows? If the latter, http://stackoverflow.com/questions/26213916/java-jtable-header-word-wrap is the easy way. – ring bearer Jul 15 '15 at 05:23
  • @ringbearer Oh nice!, html
    works so much easier, I guess I can just extend the default header renderer, modify the value and then return the super(value),
    – Aequitas Jul 15 '15 at 23:04

0 Answers0