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;
    }
}
 
I think you can just get away with calling Thread.sleep(long) method to sleep the thread for the value you generate in your random functions since you don't need perfect timings.
 
This whould work, it is hard coded to display a button every 1000 milliseconds so you'll have to change that to be random. Thread.sleep expects a long as a parameter so you'll need to generate a random long somehow.

There is also a for loop that controls how many times to display a button otherwise the game would go on forever, you can change the number to whatever you want by altering the 'numRounds' variable.

The following code should slot in at the bottom of the constructor, you could also put it in a method and call it from the constructor.

Code:
// 10 rounds
int numRounds = 10;

for (int i = 0; i < numRounds; i++) {
	buttons[getRandomInt()].setVisible(true);
	try {
		Thread.sleep(1000);
	} catch (InterruptedException e) {
		System.out.println("Thread interrupted whilst sleeping: "+e.getMessage());
	}
}
 
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
 
I'm in my second year, I'll be starting my final year in October.

The best way to tell your program how many times to run the game is to use a command line argument passed into the Main method. The Main method is used to run your program outside the development environment (I'm guessing your using BlueJ).

First you need to parameterise your constructor so you can tell it how many rounds you would like to run:

Code:
public InGame(int numRounds) {

Next you need to add the Main method so you can run your program from a command line. The if statement checks to see if a command line argument has been provided, if it hasn't then it uses a default value. A new instance of your class is then created and passed the parameter from the command line.

Code:
public static void main(String args[]) {
// default value if no command line argument is provided
int rounds = 10;
if (args.length > 0) {
	rounds = Integer.parseInt(args[0]);
}
new InGame(rounds);
}

The main method lets you execute your program from the command line using the following commands:

Compile the source code using:

javac InGame.java

Run the program:

java InGame 25

If you have created a JAR then do:

java -jar InGame.jar 25

Obviously 25 is the command line argument so you can set it to whatever.
 
Last edited:
Well there are a couple of ways to do it, do you want the time in between each button being displayed to be random? In my first post I had it fixed at 1 second by using Thread.sleep(1000)?
 
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.
 
Have you got the code you implemented? I think it's something that can be easily added in. I think I would create a variable that gets incremented with the random time you generate and then stop the program once the total of that varible is greater than or equal to the time you want (eg. 20 seconds). Here is some sort of pseudo code:

long randomTime = <whatever you did to get this number>
long totalTime;
Thread.sleep(randomTime);
totalTime += randomTime;
if (totalTime >= 20000) {
//Do something
}
 
Back
Top Bottom