jeudi 29 octobre 2015

How to set the color of a Random JButton?

I'm trying to make a simple game in java. Basicially, upon clicking a "start" JButton, 3 other buttons (labeled A, B, and C) will pop up in a separate JFrame. I want one of the buttons (a random one) to be red as soon as this second JFrame opens. Each time I click the start button, a random button must be red. In addition to that, after I click the red button, I want another random button to be red, and the cycle continues. Here is my code so far:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Driver {
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Game());
    JFrame window;
    window = new JFrame("Clicking Game");
    window.setSize(300, 300);
    JButton b = new JButton("START");
    window.setLayout(new GridLayout(5,5));
    window.add(new JLabel("INSTRUCTIONS: \n Click the 'START' button to start the game."
            + " Click as many of the red buttons as you can before time runs out!"));
    window.add(b);
    window.pack();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
    b.addActionListener(new StartButtonHandler());
    b.addActionListener(new ActualButtonHandlers());



}

}

package code;


import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

class StartButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent e){
            JFrame win = new JFrame("CLICK FAST!");
            win.setVisible(true);
            win.setSize(500, 500);
            JButton a = new JButton("A");
            JButton b = new JButton("B");
            JButton c = new JButton("C");
            win.add(a);
            win.add(b);
            win.add(c);
            win.pack();
            win.setLayout(new GridLayout(1,3));




Aucun commentaire:

Enregistrer un commentaire