Skip to content

Instantly share code, notes, and snippets.

@danielkec
Last active December 22, 2015 01:39
Show Gist options
  • Save danielkec/6397777 to your computer and use it in GitHub Desktop.
Save danielkec/6397777 to your computer and use it in GitHub Desktop.
JMenu for changing LaF of a Swing app
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
public class LafMenu extends JMenu implements ActionListener{
private static final long serialVersionUID = -8535372481219721273L;
private HashMap<String,String> lafmap = new HashMap<String,String>();
private ButtonGroup bgroup;
public LafMenu(String title) {
super(title);
addItems();
}
private void addItems() {
bgroup = new ButtonGroup();
LookAndFeelInfo[] installedLookAndFeels = UIManager.getInstalledLookAndFeels();
for (int i = 0; i < installedLookAndFeels.length; i++) {
JRadioButtonMenuItem jRadioButtonMenuItem =
new JRadioButtonMenuItem(installedLookAndFeels[i].getName());
lafmap.put(installedLookAndFeels[i].getName(),
installedLookAndFeels[i].getClassName());
this.add(jRadioButtonMenuItem);
bgroup.add(jRadioButtonMenuItem);
jRadioButtonMenuItem.addActionListener(this);
}
}
@Override
public void actionPerformed(ActionEvent e) {
String lafname = ((JRadioButtonMenuItem)e.getSource()).getText();
try {
UIManager.setLookAndFeel(lafmap.get(lafname));
SwingUtilities.updateComponentTreeUI(SwingUtilities.getRoot(this));
} catch (ClassNotFoundException |
InstantiationException |
IllegalAccessException |
UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment