1

I'm learning Java and am loving experimenting to learn new things; however, I am stuck on what I believe is a logic flaw with my program. What I want to do is have the background of my content pane change to a random color every time I click the menu item "Change Color". This works on the initial click but not on any following clicks. I have to restart the program for it to work again. Here is what I have so far...

Global:

Random rand = new Random();

float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();

Color randomColor = new Color(r,g,b);

Main():

getContentPane().setBackground(Color.WHITE);

Action Listener:

if(event.getSource().equals(i3)) { //Change Color
        getContentPane().setBackground(randomColor);
    }

i3 is my menu item "Change Color"

Thanks in advance!

camickr
  • 321,443
  • 19
  • 166
  • 288
Ardemesh
  • 11
  • 2

1 Answers1

0

In line with what these individuals have said;

  • have you tried calling repaint() - Icarus

  • You need to generate the random color in the ActionListener. - camickr

You could make a single ActionListener to repaint the JPanel's background with the random color you have created there.

Random rand = new Random();
myButton.addActionListener( 
    new ActionListener()
    {
        public void actionPerformed(ActionEvent e) 
        {   // create color values
            float r = rand.nextFloat(), g = rand.nextFloat(), b = rand.nextFloat();
            // set color values
            getContentPane().setForeground(
                new Color(r, g, b)
            );
        }
    }
);

This will randomize the color each time it is pressed by generating a new set of 3 rand.nextFloat() instead of only the first set randomized with Color randomColor = new Color(r, g, b)

Kemper Lee
  • 276
  • 4
  • 10