JayDP
JayDP

Reputation: 13

How to set JButton to change color gradually when clicked

I wanted to create JButton to change color every time it is clicked but it doesn't change after second click. It is strange because with Random().nextInt(250) instead of i it works. What could be the problem?

Here's the code:

import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class Main { public static void main(String[] args) { JFrame jf = new JFrame(); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel jp = new JPanel(); jp.setLayout(new BorderLayout(100, 100)); JButton l = new JButton("Hello"); l.setBackground(new Color(245, 12, 53)); jp.add(l, BorderLayout.EAST); jf.add(jp); jf.setSize(200, 200); jf.setLocationRelativeTo(null); jf.setVisible(true); l.addActionListener(new ActionListener() { Integer i = new Integer(0); Color c = new Color(150, 10, i); @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (i < 200) { i += 50; c = new Color(150, 10, i); l.setBackground(c); } else i = 0; } }); } }

Upvotes: 1

Views: 129

Answers (2)

camickr
camickr

Reputation: 324088

Works fine for me.

Although the code should probably be something like:

if (i < 200) 
    i += 50;
else
    i = 0;

c = new Color(150, 10, i);
l.setBackground(c);

Otherwise there will be one click that doesn't change the color.

You may want to consider using HSL Color this will allow you to change the Color in a more meaningful way by either changing the hue of the Color or shade/tone of the Color.

Upvotes: 0

Sweeper
Sweeper

Reputation: 270790

I debugged your code and saw that the value of c change, every time I click the button. The first value is (r=150,g=10,b=50), then turns into (r=150,g=10,b=100), then (r=150,g=10,b=150) etc.

This means that the color is indeed changing. It's just that the difference is too small for you to notice.

So why does random.nextInt work?

With a random value in the blue component. The value can jump very suddenly from 0 to 200. The color difference is so large that your eyes can see it. But with a gradual change of 50 every time, you only notice it the first time.

Just test it with new Color(0, 0, i). I think that will make a bigger difference. It will go from black to blue!

Upvotes: 3

Related Questions