Search code examples
javaswingjtablejtableheader

Vertical Table Header Cell Renderer


I used the Vertical Table Header Cell Renderer that is available in this site here It works great for me but I need a clue on how can I have in some headers that are vertically aligned multiple rows like this you can see in the image of the example (Coordinate Geometry). I tried to set the strings with the appropriate \n character but I think my approach is very simplistic and wrong. Please keep it simple. Thank you!


Solution

  • From Joop answer, I made this. Instead of changing the label directly you can keep your \n.

    In your file DefaultTableHeaderCellRenderer.java, replace getTableCellRendererComponent with this method :

        public Component getTableCellRendererComponent(JTable table, Object value,
                  boolean isSelected, boolean hasFocus, int row, int column) {
    
              String str = (value == null) ? "" : value.toString();
                BufferedReader br = new BufferedReader(new StringReader(str));
                String line;
                StringBuilder sb = new StringBuilder("<HTML>");
                try {
                    while ((line = br.readLine()) != null) {
                        sb.append(line).append("<br/>");
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                sb.append("</HTML>");
            super.getTableCellRendererComponent(table, sb,
                    isSelected, hasFocus, row, column);
            JTableHeader tableHeader = table.getTableHeader();
            if (tableHeader != null) {
              setForeground(tableHeader.getForeground());
            }
            setIcon(getIcon(table, column));
            setBorder(UIManager.getBorder("TableHeader.cellBorder"));
            return this;
          }