Search code examples
swinguser-interfacejava-7jtreeuimanager

Find Icon from the current LookAndFeel


I have an application that I'm creating a DefaultTreeCellRenderer. For that I want to show the default system icon from File and Directory.

At the start from the application I'm setting the System Look and Feel

java.awt.EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        try {
            // Set System L&F
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
        new App().setVisible(true);
    }
});

All UI have the System Look and Feel. But when I create a JTree with my custom DefaultTreeCellRenderer, I'm return DefaultTreeCellRenderer#getIcon the static fields bellow.

private static final Icon FILE             = UIManager.getIcon("FileView.fileIcon");
private static final Icon FOLDER           = UIManager.getIcon("FileView.directoryIcon");

The result is that the default values are from system. But the FILE and FOLDER are pointing to the default LookAndFeel.

enter image description here

How can I get the values from the System Look And Feel? To have all the same icons.


Solution

  • But the FILE and FOLDER are pointing to the default LookAndFeel.

    Well try setting the LAF for the systems you want to handle. Something like:

    UIManager.setLookAndFeel( laf1 );
    Icon laf1Icon = UIManager.getIcon("FileView.fileIcon");
    Icon laf1Folder = UIManager.getIcon("FileView.directoryIcon");
    UIManager.setLookAndFeel( laf2 );
    Icon laf2Icon = UIManager.getIcon("FileView.fileIcon");
    Icon laf2Folder = UIManager.getIcon("FileView.directoryIcon");
    //...
    UIManager.setLookAndFeel( backToTheDefault );
    

    You can see the results of this approach by checking out UIManager Defaults. As the change the LAF the Icons changes. Of course this will only work for LAF's available on your system, not all possible remote file systems.