Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Java (http://www.programmingforums.org/forum17.html)
-   -   Applet / Button problem. (http://www.programmingforums.org/showthread.php?t=13077)

TCStyle Apr 28th, 2007 6:48 PM

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);
        }
    }
}


Serinth Apr 29th, 2007 12:10 PM

did you try making an event listener class with a button object and then pass your button to that event listener and then in actionPerformed do the setBackground.


All times are GMT -5. The time now is 2:11 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC