Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
1 total  XML / RSS feed 

JMenu that switches between Swing LookAndFeel themes.

// This creates a tiny JFrame with a menu, which changes the LookAndFeel.

package looksAndFeels;

import javax.swing.*;
import javax.swing.UIManager.*;
import java.awt.event.*;

public class ThemeChanger extends JFrame {

        ThemeChanger __instance;
        
        public ThemeChanger() {
                super("Swing Theme Changer");
                __instance = this;
                this.setSize(400, 200);
                
                JMenuBar appMenu = new JMenuBar();
                appMenu.add(makeLaFMenu());
                this.setJMenuBar(appMenu);
                
                this.setVisible(true);
        }
        
        private JMenu makeLaFMenu() {
                JMenuItem tempItem;
                JMenu lafMenu = new JMenu("Supported Themes");
                LookAndFeelInfo[] supportedLAFs = UIManager.getInstalledLookAndFeels();
                for (int ii = 0; ii < supportedLAFs.length; ii++) {
                        LookAndFeelInfo currentLAF = supportedLAFs[ii];
                        tempItem = new JMenuItem(currentLAF.getName());
                        tempItem.setActionCommand(currentLAF.getClassName());
                        tempItem.addActionListener(new myListener());
                        lafMenu.add(tempItem);
                }
                
                return lafMenu;
        }
        
        class myListener implements ActionListener {

                public void actionPerformed(ActionEvent event) {
                        try {
                                UIManager.setLookAndFeel(event.getActionCommand());
                        } catch (Exception e) {
                                ; // No exceptions will happen (barring some unforeseen catastrophe),
                                  // because we only grabbed the supported LaF's.
                        }
                        SwingUtilities.updateComponentTreeUI(__instance);
                }
                
        }
        
        public static void main(String[] args) {
                new ThemeChanger();
        }

}

« Newer Snippets
Older Snippets »
1 total  XML / RSS feed