javaswinguimanager

Java Swing UIManager with tableHeaderUI


Following this list http://thebadprogrammer.com/swing-uimanager-keys/, everything related to font and colors it's ok but im trying to set deafult heights for components and every single component on that list has a xxxUI, which i have no idea how to implement.

I tried to

UIManager.put("TableHeaderUI", new TableHeaderUI() {
        //it crashes empty aswell
        @Override
        public Dimension getPreferredSize(JComponent c) {
            return super.getPreferredSize(c);
        }
    });

but at runtime it crashes and every table header is gone, heres the error message...

UIDefaults.getUI() failed: no ComponentUI class for: javax.swing.table.JTableHeader[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,border=,flags=16777224,maximumSize=,minimumSize=,preferredSize=,draggedDistance=0,reorderingAllowed=true,resizingAllowed=true,updateTableInRealTime=true]
java.lang.Error
    at javax.swing.UIDefaults.getUIError(Unknown Source)
    at javax.swing.MultiUIDefaults.getUIError(Unknown Source)
    at javax.swing.UIDefaults.getUI(Unknown Source)
    at javax.swing.UIManager.getUI(Unknown Source)
    at javax.swing.table.JTableHeader.updateUI(Unknown Source)
    at javax.swing.table.JTableHeader.<init>(Unknown Source)
    at javax.swing.JTable.createDefaultTableHeader(Unknown Source)
    at javax.swing.JTable.initializeLocalVars(Unknown Source)
    at javax.swing.JTable.<init>(Unknown Source)
    at javax.swing.JTable.<init>(Unknown Source)

None seems to use this property, i haven't found a specific example of this.


Solution

  • You spoiled the UIManager because you put an object of wrong type for key "TableHeaderUI".

    Instead, for key "TableHeaderUI" the value is supposed to be a String (giving the fully-qualified name of a class implementing interface javax.swing.plaf.TableHeaderUI).

    For example you can do like this:

    UIManager.put("TableHeaderUI", MyTableHeaderUI.class.getName());
    

    with an implementation class like this:

    public class MyTableHeaderUI extends BasicTableHeaderUI {
    
        // UIDefaults.getUI(JComponent) will call this method via reflection
        public static ComponentUI createUI(JComponent h) {
            return new MyTableHeaderUI();
        }
    
        @Override
        public Dimension getPreferredSize(JComponent c) {
            return super.getPreferredSize(c);
        }
    }
    

    A special thing (far from obvious) is: You need to implement your own static createUI(JComponent) method, or else your UI class will never be instantiated. See the javadoc of UIDefaults.getUI(JComponent).