2

I've written a JApplet and I set, in the initialization, colors for the Nimbus L&F.

When I run the applet, both via Netbeans or via Google Chrome, 9/10 times it happens that button background is set to dark, but sometimes Nimbus is not able to set the color.

Here is a SSCCE:

import java.awt.Color;
import java.lang.reflect.InvocationTargetException;
import javax.swing.UIManager;

public class NimbusColors extends javax.swing.JApplet {

    // colors and look and feel
    Color buttonBackgroundColor;
    Color buttonTextColor;
    Color textAreaBackgroundColor;
    Color textAreaTextColor;
    Color skinColor;
    Color defaultButtonBackgroundColor = Color.decode("#4a4a4a");
    Color defaultButtonTextColor = Color.decode("#cecece");
    Color defaultTextAreaBackgroundColor = Color.decode("#414141");
    Color defaultTextAreaTextColor = Color.decode("#cecece");
    Color defaultSkinColor = Color.decode("#353535");
    Color progressColor = Color.decode("#00FFFF");

    @Override
    public void init() {

        getContentPane().setBackground(defaultSkinColor);
        UIManager.put("TextArea.background", defaultTextAreaBackgroundColor);
        UIManager.put("TextArea.foreground", defaultTextAreaTextColor);
        UIManager.put("control", defaultTextAreaBackgroundColor);
        UIManager.put("nimbusLightBackground", defaultSkinColor);
        UIManager.put("background", defaultSkinColor);
        UIManager.put("text", defaultButtonTextColor);
        UIManager.put("ComboBox.background", defaultSkinColor.darker().darker());
        UIManager.put("Button.background", defaultSkinColor);
        UIManager.put("info", defaultSkinColor.brighter().brighter());

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NimbusColors.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        /* Create and display the applet */
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    initComponents();
                }
            });
        } catch (InterruptedException | InvocationTargetException ex) {
            System.exit(11);
        }
    }

    private void initComponents() {

        jButtonBrowseFS = new javax.swing.JButton();

        jButtonBrowseFS.setText("Browse");
        jButtonBrowseFS.setToolTipText("Browse your filesystem to select files to upload");
        jButtonBrowseFS.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jButtonBrowseFS.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonBrowseFS)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButtonBrowseFS)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }              
    private javax.swing.JButton jButtonBrowseFS;
}

I've tried this code with Netbeans 7.3.1, creating a new Java Project and adding a new JApplet file. If I run the file from Netbeans a dozen times, sometimes button background is dark, sometimes it's not.

Can anyone replicate this strange behavior? What is going on?

Update 1: I'm running Windows 8 Pro

Paolo M
  • 12,403
  • 6
  • 52
  • 73
  • 1
    @hellzone I'm using jdk1.7.0_25. Try to resize the window, click the button etc. and retry, please. I don't think it depends on the netbeas version, because I have similar problems when running the complet applet in Google Chrome – Paolo M Jul 10 '13 at 10:10
  • I have tried all of things but nothing changed. Install jdk 1.6 and try with using it. jdk 1.7 can be the problem. – hellzone Jul 10 '13 at 10:12
  • @hellzone In the actual applet I use Java 7 features, so if it's a Java 7 bug I have to take it... – Paolo M Jul 10 '13 at 10:15
  • I just removed multi-catch statements which are not supported by 1.6 – hellzone Jul 10 '13 at 10:17
  • @hellzone I did intensive use of the Files class. – Paolo M Jul 10 '13 at 10:31
  • 1
    @PaoloM : 99.9 % of people on Stackoverflow, might won't even try to test your case, for a single reason, __They might hesitate to build one html file to test this code of yours__ . In order for someone to test your code, in an easier manner, while posting code related to `JApplet/Applet`, one must insert this small line too in the `.java file`, so that one doesn't have to write the html file. `/***/` Now one can simply write `javac NimbusColors.java` to compile and then `appletviewer NimbusColors.java` to run it :-) – nIcE cOw Jul 10 '13 at 12:40
  • I guess, this is the issue we talking about, as seen in this [abnormal snapshot](http://prntscr.com/1elfvf), the Button appears Gray in colour, instead of being Dark, as seen in this [dark snapshot](http://prntscr.com/1elfmk), as intended. – nIcE cOw Jul 10 '13 at 12:48
  • @nIcEcOw The issue is that sometimes I got the button as in your snapshot, but often I got [this](http://postimg.org/image/m23766n8j/). Without modifying the code or recompiling, obviously :) – Paolo M Jul 10 '13 at 12:55
  • 1
    @PaoloM : Same here, just for once, in many tries, I get this white Button, though most of the time it's gray, might be it's a bug in `Nimbus`, it has some issues always :( – nIcE cOw Jul 10 '13 at 13:04

3 Answers3

2

I tried your code but It always shows same colors. I think there is a problem with your Netbeans or jdk version. I am using Netbeans 7.3 and jdk 1.6. enter image description here

hellzone
  • 5,393
  • 25
  • 82
  • 148
  • @mKorbel Code working for me guys. I don't know its related with netbeans or JDK but code is working perfectly :) – hellzone Jul 10 '13 at 10:14
  • @hellzone Code is not working for you... the working one set button background color to dark. – Paolo M Jul 10 '13 at 10:39
2
  • for JButton is there used Painter, Background is ignored by default

  • there aren't changes betweens Java6/7

  • not all Keys works as we expected, Nimbus has a lots of suprices (solved in two-three custom L&F based on Nimbus)

  • one of ways, works for me in all cases, intentionally delayed by using Swing Timer, for example

enter image description here

Color.decode("#353535"); returns

enter image description here

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.LookAndFeel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;

public class NimbusTest3 {

    private static final long serialVersionUID = 1L;
    private javax.swing.JButton button;
    private JFrame frame = new JFrame();
    private Timer t;

    public NimbusTest3() {
        button = new javax.swing.JButton();
        button.setText("Text");
        frame.add(button);
        frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        t = new Timer(1000, new ActionListener() {
            private Random r = new Random();

            @Override
            public void actionPerformed(ActionEvent e) {
                Color c = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256));
                try {
                    LookAndFeel lnf = UIManager.getLookAndFeel().getClass().newInstance();
                    UIDefaults uiDefaults = lnf.getDefaults();
                    uiDefaults.put("nimbusBase", c);
                    UIManager.getLookAndFeel().uninitialize();
                    UIManager.setLookAndFeel(lnf);
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }
                UIDefaults defaults = UIManager.getDefaults();
                defaults.put("Button.background", c);
                SwingUtilities.updateComponentTreeUI(button);
                t.stop();
            }
        });
        t.start();
    }

    public static void main(String args[]) {
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
            return;
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                NimbusTest3 nimbusTest3 = new NimbusTest3();
            }
        });
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • What do you mean that "Background is ignored by default"? If I comment the line which set the Button.background, I always have a ligth button, else it happens just sometimes. – Paolo M Jul 10 '13 at 10:39
  • Painter is responsible to apply, paint Gradient background – mKorbel Jul 10 '13 at 10:44
  • Sorry, but I don't understand. – Paolo M Jul 10 '13 at 10:53
  • this happends every time when OPs never to read [Oracle tutorial](http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/custom.html) and never to check [Nimbus defaults](http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/_nimbusDefaults.html#primary) :-) .. , for [Buttons Components](http://docs.oracle.com/javase/tutorial/uiswing/components/button.html) is there used [Painter](http://stackoverflow.com/a/11803010/714968), in the case that you change `Nimbus overrides` (not all keys are really corresponding with overrides), then `Button.background` can by accepted by Java compiler – mKorbel Jul 10 '13 at 11:01
  • Ok, thanks. For curiosity... have you tried to reproduce the strange bahaviour in my question? I can't understand why same code (even without recompiling) behaves differently on different runs... – Paolo M Jul 10 '13 at 11:08
  • I wouldn't need that, I'm expected default light_grey Color for JButton, (funny could be that sometimes works), commented this issue a few times, – mKorbel Jul 10 '13 at 11:10
  • nimbus is too buggy, can't simulating, :-) you are one of confused users, there are three ways, use 1. another and custom L&F, 2. custom L&F based on Nimbus, 3. safest SystemLookAndFeel – mKorbel Jul 10 '13 at 11:26
0

I've finally found a workaround.

In netbeans, I've set the background property of the button to some value (different from the one I want, but different from the default 240,240,240 too).

When I run the applet, now I always get what I expect, that is the color set in the code with Nimbus.

Paolo M
  • 12,403
  • 6
  • 52
  • 73