Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

java - How to change the background color for JPanels with Nimbus Look and Feel?

I want to use a different background color for all my JPanels in an application. How can I do that when using Nimbus Look and Feel?

I follow Changing the Color Theme to change the color of components in Nimbus Look and Feel.

It only works sometimes, randomly. If I set a PropertyChagneListener before I change the color, it is only notified once.

Here is some test code:

public class RedPanels extends JFrame {

  public RedPanels() {
    JPanel panel = new JPanel();
    add(panel);
    setPreferredSize(new Dimension(100, 100));
    pack();
    setVisible(true);
  }

  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

      @Override
      public void run() {

        try {
          for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                UIManager.setLookAndFeel(info.getClassName());
                UIManager.getDefaults().addPropertyChangeListener(
                                               new PropertyChangeListener() {

                  @Override
                  public void propertyChange(PropertyChangeEvent event) {
                    if (event.getPropertyName().equals("Panel.background")) {
                      System.out.println("color changed");
                    }

                });
                UIManager.put("Panel.background", new Color(255,0,0));
                break;
            }
          }
        } catch (Exception e) {
            // Nimbus is not available.
        }
        new RedPanels();
        }
    });
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
UIManager.getLookAndFeelDefaults().put("Panel.background", Color.RED);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...