1

So it seems like theres a bug on my end, because the exact same code works for a friend, but does not for me. Note: I use mac os and the newest version of eclipse.

But whats my problem? Trying to use setBackground(Color.something) for JButtons does not work as it should. When starting the program below, the buttons background should be red like this:

https://i.stack.imgur.com/iuTCT.jpg

For me, it just looks like this

https://i.stack.imgur.com/Fw79L.png

So nothing really happens, setForeground works as expected. Using setBackground on Frame or TextField also works as expected. It just does not work on Buttons, JButtons for me. Someone knows any reason for that?

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class Test extends JFrame {
    JButton[] button = new JButton[10];

    public Test() {
        setLayout(new FlowLayout());
        for(int i = 0; i < 10; i++) {
            button[i] = new JButton("" + i);
            add(button[i]);
        }
        for (int i = 0; i < 10; i++) {
            button[i].setBackground(Color.green);
        }
        setSize(250,200);
        setVisible(true);
    }

    public static void main(String[] args) {
        Test test = new Test();
    }
}
camickr
  • 321,443
  • 19
  • 166
  • 288
J.Dupla
  • 65
  • 4
  • Look at MrSmileFace's answer in the other question... You must call: `button.setOpaque(true);` and `button.setBorderPainted(false);` on your `JButton`. I recently had this same issue 4-5 days ago, that did the trick. I started the code in Ubuntu, then continued it in Mac and that thing happened to me, but using both commands in this comment did the trick :) – Frakcool Mar 24 '18 at 00:23
  • It worked out, thanks. Someone also suggested to change the look and feel to the cross platform look and feel. SetBackground works without any problems if you do it and i think its also better to use the cross platform one to understand how the GUI looks on a platform not being a mac os. Because as you see above, the GUI looks really different on windows(pic above from my friend) and on my mac os. – J.Dupla Mar 24 '18 at 00:30
  • It depends on your needs :) But glad it worked – Frakcool Mar 24 '18 at 00:31
  • @J.Dupla The primary differences likely come down to the look and feel been used by default. You need to disable the delegates functionality - which I demonstrated today on [this question](https://stackoverflow.com/questions/49459042/change-buttons-backgroundcolor-in-awt) which demonstrates the functionality under MacOS – MadProgrammer Mar 24 '18 at 01:25

0 Answers0