View Single Post
Old Apr 28th, 2007, 5:48 PM   #1
TCStyle
Programmer
 
Join Date: Jan 2005
Location: Albany, NY
Posts: 43
Rep Power: 0 TCStyle is on a distinguished road
Applet / Button problem.

I have a 200 x 200 applet with 3 buttons. My script generates a random number between 0-2 that is used as an index to my array (which contains the variable names of my buttons). I want it so that when the user clicks the button that was randomly chosen out of my array, it turns red, else it turns blue. I know how to detect if the random button was click, but I don't know to to then change the color of that button.
Script:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class Game extends Applet implements ActionListener {
    private Button b1, b2, b3, rndB;
    private int randNum = (int)(Math.random()*3);
    private String buttonArray[] = {"b1", "b2", "b3"};
    private String randButton = buttonArray[randNum];
    
    public void init() {
        setBackground(Color.WHITE);
        
        b1 = new Button("b1");
        b1.setBackground(Color.BLACK);
        b1.addActionListener(this);
        add(b1);
        
        b2 = new Button("b2");
        b2.setBackground(Color.BLACK);
        b2.addActionListener(this);
        add(b2);
        
        b3 = new Button("b3");
        b3.setBackground(Color.BLACK);
        b3.addActionListener(this);
        add(b3);
        
        setSize(200, 200);
    }
        
    public void actionPerformed(ActionEvent e) {
        Object test;
        if (e.getActionCommand()==randButton) {
            test = e.getSource();
            test.setBackground(Color.RED);
        } else {
            test.setBackground(Color.BLUE);
        }
    }
}
__________________
meh...
TCStyle is offline   Reply With Quote