Reputation: 1
I'm trying to implement a theme switcher in a simple application, I followed some topics on the internet on how to change components colors and such, but I'm having some trouble trying to get the JMenu to change color in both clicking the corresponding Menu Item and in using the shortcut that I designated to it. Here is a short version of what I'm trying to do:
public class DarkThemeTest
{
private static Boolean DarkTheme= false;
public static void main(String[] args)
{
String nimbusBase=new String(String.valueOf(UIManager.getColor("nimbusBase")));
try
{
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch (Exception e)
{
e.printStackTrace();
}
JFrame frame=new JFrame("Dark Theme On JMenuTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
JLayeredPane pane=new JLayeredPane();
pane.setLayout(null);
frame.add(pane);
JMenuBar menuBar=new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mView=new JMenu("View");
menuBar.add(mView);
mView.setMnemonic(KeyEvent.VK_V);
JMenuItem mInvTheme=new JMenuItem("Change Theme");
mView.add(mInvTheme);
mInvTheme.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, ActionEvent.CTRL_MASK));
mInvTheme.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if(DarkTheme==false) // Set the dark theme
{
frame.getContentPane().setBackground(Color.black);
UIManager.put("nimbusBase", Color.black);
SwingUtilities.updateComponentTreeUI(frame);
menuBar.setBackground(Color.black);
mView.setForeground(Color.white);
mInvTheme.setForeground(Color.white);
DarkTheme=true;
}
else // Set the light theme
{
UIManager.put("nimbusBase",Color.getColor(nimbusBase));
try
{
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch (Exception error)
{
error.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(frame);
menuBar.setBackground(Color.white);
mView.setForeground(Color.black);
mInvTheme.setForeground(Color.black);
frame.getContentPane().setBackground(Color.white);
DarkTheme=false;
}
}
});
frame.setVisible(true);
}
}
Problem is: shortcut works, clicking the menu item don't. They are, in theory, executing the same block of code, and all the other components on the application window are changing as expected except for the JMenu bar.
Appreciate any help on the subject!
Upvotes: 0
Views: 54