1

My current java version is:

$java -version
 java version 1.8.0_40

I'm very new to swing and trying to write my first minesweeper app. Now, I need to disable a button when clicking on it and print a number of adjacent mines (with the appropriate text color depending on a number: 1- blue, 2 - green, 3 - red, etc). So as suggested in this answer I wrote the following:

JFrame frame = new JFrame("Hello swing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JButton button = new JButton();
button.addActionListener((ActionEvent ev) -> { 
                        button.setSelected(true);  
                        button.setText("<html><font color = red>3</font></html>");
                        button.setEnabled(false); });

But it still goes grey when disabling:

enter image description here

But enabled button look just as I want it to:

enter image description here

What to do with this issue? How to fix this problem with disabling buttons?

Community
  • 1
  • 1
  • Have you tried setting the text after disabling it? It may be that disabling the button overrides the formatting. – CubeJockey Apr 15 '16 at 16:36
  • @CubeJockey Just tried, the result is the same... –  Apr 15 '16 at 16:37
  • Possible duplicate of [Text is greyed out when JButton is disabled](http://stackoverflow.com/questions/9008814/text-is-greyed-out-when-jbutton-is-disabled) It looks like you guys are using the same textbook. – Pete B. Apr 15 '16 at 16:37
  • Interesting. Thanks for the feedback, I'll keep an eye out. – CubeJockey Apr 15 '16 at 16:37
  • @PeteBelford Yes, I checked this answer. But I use jre_1.8. Maybe it has something ot do with it...? –  Apr 15 '16 at 16:50
  • @PeteBelford java version "1.8.0_40" –  Apr 15 '16 at 16:51
  • @CubeJockey Maybe you know some workarounds...? –  Apr 15 '16 at 16:52

1 Answers1

2

Maybe you know some workarounds

Use Icons instead of text.

Then you can use:

JButton button = new JButton( icon3 );
button.setDisabledIcon( icon3 );
camickr
  • 321,443
  • 19
  • 166
  • 288
  • Works perfect, but I have to also call to `setIcon( icon3 )` in order for disbled icon works correctly. –  Apr 15 '16 at 17:04
  • Seems a little bit as miracle... why doesn't it work without `setIcon ( icon3 )`? –  Apr 15 '16 at 17:05
  • @DmitriiBundin The disabled icon is meant to replace the original icon, not the text. It doesn't make sense to have both text and an icon because then they would be painted side by side. – camickr Apr 15 '16 at 18:04