views:

613

answers:

2

Greetings,

So far, my code compiles, but it changes white to black and then don't want to change. Supposely it should change from red->orange->green->pink->blue->black..

public void init() {
    c=new Color[] {Color.red, Color.orange, Color.green, 
                   Color.pink, Color.blue, Color.black };
    btnNext = new Button("Next Color");
    btnNext.addActionListener(this);
    setLayout(new BorderLayout());
    add(btnNext, BorderLayout.SOUTH);
}

public void paint(Graphics g) { }

public void actionPerformed(ActionEvent e) {
    if(e.getSource() == btnNext) {
     for(int n=0;n<6;n++) {
   setBackground(c[n]);
     }
    repaint();
    }
}

Thank you for your help.

A: 

What's happening is that you're looping through all of the colors all at once, every time the btnNext action is triggered. It goes by so fast that you do not see the other colors.

What I would do is have a variable that keeps track of what position in the array you are in, and have that variable be incremented when the user hits next, and then change the background to that color. You have to get rid of the for loop inside your actionPerformed.

AlbertoPL
+1  A: 

What you need to do is keep an int member variable of the current position in the array. Then increment that position every time you click the button.

// New int keeping track of background pos
private int arrPos;

public void init() {
    c=new Color[] {Color.red, Color.orange, Color.green, 
                   Color.pink, Color.blue, Color.black };
    // initialize the int
    arrPos = 0;
    btnNext = new Button("Next Color");
    btnNext.addActionListener(this);
    setLayout(new BorderLayout());
    add(btnNext, BorderLayout.SOUTH);
}

public void paint(Graphics g) { }

public void actionPerformed(ActionEvent e) {
    if(e.getSource() == btnNext) {
        // increment the background
        arrPos++;
        if (arrPos >= c.length) arrPos = 0;
        setBackground(c[arrPos]);
        repaint();
    }
}
jjnguy
If you override your paint() method with an empty method won't the applet not be drawn at all after a repaint?
mjh2007
@mjh2007I wouldn't recommend overriding paint with a blank method. I was just showing that the paint method didn't need to change for the background color to change.
jjnguy