0

I am programming in JAVA and my OS is MAC. I am trying to setForeground or even setBackground of my JButtons, but no progress. I have added:

button.setOpaque(true); 
button.setBorderPainted(false);

But still, no changes! How can I change the colour of my JButtons?

Here is my Code:

    public class New_button extends JButton{
    String up = new String("<html><font color=BLACK>^<size=50></font></html>");
    String down = new String("<html><font color=BLACK>v<size=50></font></html>");
    double value;
    int foldChange;

    public New_button(double val, int foldChan) {
        value = val;
        foldChange = foldChan;
        this.setSize(30, 30);
        this.setFont(this.getFont().deriveFont(50.0f));
        this.setBorder(null);
    }

    public void changeColor(double value){
         try {
                UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
             } catch (Exception e) {
                        e.printStackTrace();
             }
        if(value > 0.05){
            this.setForeground(Color.YELLOW);
            this.setOpaque(true);
            this.setBorderPainted(false);

        }
        else{
            this.setForeground(Color.RED);
            this.setOpaque(true);
            this.setBorderPainted(false);
        }
    }

    public void changeLable(int foldChange){
        if(foldChange == 1)
            this.setText(up);
        else
            this.setText(down);
    }    
}

Thanks

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 1
    If you immediately use `setBackground(Color.RED)` in the constructor `New_button`? (Maybe changeColor needs to be called wrapped in an `EventQueue.invokeLater(new Runnable())`) Furthermore use `setLookAndFeel` once, in the `main` for instance. – Joop Eggen Sep 09 '13 at 13:30
  • @Joop Eggen good point, because there I miss another important code line for refresh L&F – mKorbel Sep 09 '13 at 13:40
  • @Rozita Akrami you code is wrong designed, remove L&F settings in this code block – mKorbel Sep 09 '13 at 13:41
  • Also consider this [alternate approach](http://stackoverflow.com/a/3420431/230513). – trashgod Sep 09 '13 at 15:30

1 Answers1

0

Check this way:

JButton button = new JButton("test");
button.setBackground(Color.RED);
button.setOpaque(true);

source

Community
  • 1
  • 1
  • Actually, if you are wondering about the correction of my method I should say it is working properly. Also changeLable is working well. – Rozita Akrami Sep 09 '13 at 13:36
  • Try to avoid setting look and feel in your code and check, how does it work. I think L&F setting may affect to button color change. –  Sep 09 '13 at 13:47
  • No, I think I made a mistake, it wasn't look and feel. If I remove look and feel it doesn't colour the buttons any more! – Rozita Akrami Sep 11 '13 at 08:46