Java help!

Associate
Joined
18 Mar 2007
Posts
291
Afternoon gents,

I'm having a little trouble getting something working.

Basically, i've got a little program that will work like a "whack the weasel" type game.

At the moment, i've created the program and certain functions, but what I can't get working is waiting a random amount of time and then displaying a random button (I'm working with an array of buttons at the moment, but will change that to an array of images later).

So, what I want to happen is when the window opens, I want it to wait a random amount of time and the display a random button (Random functions already created).

Here's my class:

Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Random;

public class InGame extends JFrame
{
    private String[] numbers = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
    private JButton[] buttons = new JButton[numbers.length];
    
    public InGame() {
        
    
        this.setSize(700,700);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("Whack the Weasel!");
        
        ClickListener c1 = new ClickListener();
        
        JPanel panel2 = new JPanel();
        panel2.setSize(500,500);
        panel2.setLayout(new GridLayout(0,3,20,20));
        

        // create instance of each button
        for (int i = 0; i < numbers.length; i++){
            buttons[i] = new JButton(numbers[i]);
            buttons[i].addActionListener(c1);
            buttons[i].setVisible(false);
            panel2.add(buttons[i]);
        }
        
        this.getContentPane().add(panel2);
        
        this.setVisible(true);
    }
    
    //When button is clicked, make the buttons disappear
    private class ClickListener
        implements ActionListener
    {        
        public void actionPerformed(ActionEvent e)
        {
            for(int j=0; j<numbers.length; j++) {
                if(e.getSource()==buttons[j])
                    buttons[j].setVisible(false);
            }

        }
   }
   
   //Methods here:
   
    private double getRandomDouble(double lower, double higher)
    {
        double a;
        a = Math.random();
        while (a < lower || a > higher) {
            a = Math.random();
        }
        return a;
    }
    
    private int getRandomInt()
    {
        Random randomGenerator;
        randomGenerator = new Random();
        int index = randomGenerator.nextInt(9);
        return index;
    }
}
 
Hi, infact that was going to be the next part of my problem (the for loop). i want to run the program for a certain amount of time (given as a parameter), what would be the best way to implement this?

Cheers, Rob
 
yeah, i want that time to be random - i've implemented this already, but i also want to run this whole program for 20 seconds. i.e: keep displaying random buttons at random times for 20 seconds.
 
Back
Top Bottom