12 Replies - 1202 Views - Last Post: 13 May 2010 - 10:54 AM Rate Topic: -----

#1 Guest_Simon*


Reputation:

Waiting in Java

Posted 13 May 2010 - 05:31 AM

Could I please get some help? I made a matching game program and almost everything works, the only issue is that after you click the second button, if they are different it should wait two seconds before it hides them again, but it waits before it shows the second one you click on.

PS the reason the names of the classes are tic tac toe and such is because i just changed a tic tac toe program i made


/**
 * Simon Kapiamba
 * 4/7/10
 * 
 */
package tic;
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
@SuppressWarnings("serial")
public class TicTacToe extends JFrame implements ActionListener{
	Container contentPane;
	JButton rePlay;
	JButton show;
	JLabel message;
	int tempVal;
	int count;
	int tempN;
	int first;
	char tempC;
	int second;
	int turn;
	int pairs = 0;
	int r = 0;
	char winner = '*';
	char [] clickVal = new char[16];
	Color c = new Color(255, 255, 200);
	JButton [] board = new JButton[16];
	char [] value = new char[16];
	Font fonts  = new Font("Arial", Font.BOLD, 72);
	public static void main(String[] args){
		TicTacToe window = new TicTacToe();
		window.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}

	public TicTacToe(){
		super("Tic Tac Toe");
		setBounds(0, 0, 900, 400);
		contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());
		message = new JLabel("");
		rePlay = new JButton("reset");
		show = new JButton("solution");
		rePlay.addActionListener(this);
		JPanel panelBoard = new JPanel(new GridLayout(4,4));
		JPanel panel = new JPanel(new FlowLayout());
		panel.add(show);
		panel.add(message);
		panel.add(rePlay);
		int count = 0;
		for(int i = 0; i < board.length; i++){
			if(i%2 == 0)
				count++;
			value[i] = (char)(count+64);
			clickVal[i] = '*';
			board[i] = new JButton();
			board[i].addActionListener(this);
			r = i + 1;
			String temp = new String (" " + r);
			board[i].setText(temp);
			panelBoard.add(board[i]);
			board[i].setFont(fonts);
			winner = '*';
			c = new Color(165, 211, 69);
			board[i].setBackground(c);
		}
		shuffle(value);
		contentPane.add(panelBoard,BorderLayout.CENTER);
		contentPane.add(panel,BorderLayout.SOUTH);
		setVisible(true);
	}

	public void actionPerformed(ActionEvent e){
		String a = e.getActionCommand();
		a = a.substring(1);
		tempC = a.charAt(0);
		//System.out.println(tempC);
		if(a.equals("eset")){
			shuffle(value);
			message.setText("");
			for(int i = 0; i < board.length; i++){
				pairs = 0;
				clickVal[i] = '*';
				board[i].setText(new String(" " + (i+1)));
			}
		}else if(a.equals("olution")){
			for(int i = 0; i < board.length; i++){
				board[i].setText(new String(" ") + value[i]);
			}
			message.setText("Press 'reset' to start a new game!");
		}else if(tempC != 'A' && tempC != 'B' && tempC != 'C' && tempC != 'D' && tempC != 'E' && tempC != 'F' && tempC != 'G' && tempC != 'H'){
			tempN = new Integer(a);
			if(turn%2 == 0 && clickVal[tempN-1] == '*'){
				first = tempN - 1;
				clickVal[first] = ' ';
				board[first].setText(new String(" " + value[first]));
				turn++;
			}
			else if(turn%2 == 1 && first != tempN-1){
				second = tempN - 1;
				clickVal[second] = ' ';
				board[second].setText(new String(" " + value[second]));
				repaint();
				turn++;
				if(value[first] != value[second]){
					board[first].setText(new String(" " + (first+1)));
					clickVal[first] = '*';
					board[second].setText(new String(" " + (second+1)));
					clickVal[second] = '*';
				}else{
					pairs++;
				}
				if(pairs == 8){
					message.setText("You win!");
				}
			}	
		}
	}

	static void wait(int n){
		long t0,t1;
		t0=System.currentTimeMillis();
		do{
			t1 = System.currentTimeMillis();
		}
		while(t1-t0<n);
	}

	static void shuffle(char [] a){
		int f;
		int s;
		char hold;
		for(int i = 0; i < 100; i++){
			f = (int) (Math.random()*16);
			s = (int) (Math.random()*16);
			hold = a[f];
			a[f] = a[s];
			a[s] = hold;
		}
	}
}


Is This A Good Question/Topic? 0

Replies To: Waiting in Java

#2 Guest_simon*


Reputation:

Re: Waiting in Java

Posted 13 May 2010 - 05:35 AM

to make it easier to understand, here is where im having the issue:

if(turn%2 == 0 && clickVal[tempN-1] == '*'){ // first click
				first = tempN - 1;
				clickVal[first] = ' ';
				board[first].setText(new String(" " + value[first]));
				turn++;e
			}
			else if(turn%2 == 1 && first != tempN-1){ //second click
				second = tempN - 1;
				clickVal[second] = ' ';
				board[second].setText(new String(" " + value[second]));
				repaint();
				turn++;
				wait(2000); // this is where i go to the wait method

Was This Post Helpful? 0

#3 Guest_simon*


Reputation:

Re: Waiting in Java

Posted 13 May 2010 - 05:38 AM

two things, one i fail at removing my name from things i post on the internet, two the first time i posted all of the code i made a mistake

/** 
 * 4/7/10 
 *  
 */ 
package tic; 
import javax.swing.*; 
 
import java.awt.*; 
import java.awt.event.*; 
@SuppressWarnings("serial") 
public class TicTacToe extends JFrame implements ActionListener{ 
        Container contentPane; 
        JButton rePlay; 
        JButton show; 
        JLabel message; 
        int tempVal; 
        int count; 
        int tempN; 
        int first; 
        char tempC; 
        int second; 
        int turn; 
        int pairs = 0; 
        int r = 0; 
        char winner = '*'; 
        char [] clickVal = new char[16]; 
        Color c = new Color(255, 255, 200); 
        JButton [] board = new JButton[16]; 
        char [] value = new char[16]; 
        Font fonts  = new Font("Arial", Font.BOLD, 72); 
        public static void main(String[] args){ 
                TicTacToe window = new TicTacToe(); 
                window.setDefaultCloseOperation(EXIT_ON_CLOSE); 
        } 
 
        public TicTacToe(){ 
                super("Tic Tac Toe"); 
                setBounds(0, 0, 900, 400); 
                contentPane = getContentPane(); 
                contentPane.setLayout(new BorderLayout()); 
                message = new JLabel(""); 
                rePlay = new JButton("reset"); 
                show = new JButton("solution"); 
                rePlay.addActionListener(this); 
                JPanel panelBoard = new JPanel(new GridLayout(4,4)); 
                JPanel panel = new JPanel(new FlowLayout()); 
                panel.add(show); 
                panel.add(message); 
                panel.add(rePlay); 
                int count = 0; 
                for(int i = 0; i < board.length; i++){ 
                        if(i%2 == 0) 
                                count++; 
                        value[i] = (char)(count+64); 
                        clickVal[i] = '*'; 
                        board[i] = new JButton(); 
                        board[i].addActionListener(this); 
                        r = i + 1; 
                        String temp = new String (" " + r); 
                        board[i].setText(temp); 
                        panelBoard.add(board[i]); 
                        board[i].setFont(fonts); 
                        winner = '*'; 
                        c = new Color(165, 211, 69); 
                        board[i].setBackground(c); 
                } 
                shuffle(value); 
                contentPane.add(panelBoard,BorderLayout.CENTER); 
                contentPane.add(panel,BorderLayout.SOUTH); 
                setVisible(true); 
        } 
 
        public void actionPerformed(ActionEvent e){ 
                String a = e.getActionCommand(); 
                a = a.substring(1); 
                tempC = a.charAt(0); 
                //System.out.println(tempC); 
                if(a.equals("eset")){ 
                        shuffle(value); 
                        message.setText(""); 
                        for(int i = 0; i < board.length; i++){ 
                                pairs = 0; 
                                clickVal[i] = '*'; 
                                board[i].setText(new String(" " + (i+1))); 
                        } 
                }else if(a.equals("olution")){ 
                        for(int i = 0; i < board.length; i++){ 
                                board[i].setText(new String(" ") + value[i]); 
                        } 
                        message.setText("Press 'reset' to start a new game!"); 
                }else if(tempC != 'A' && tempC != 'B' && tempC != 'C' && tempC != 'D' && tempC != 'E' && tempC != 'F' && tempC != 'G' && tempC != 'H'){ 
                        tempN = new Integer(a); 
                        if(turn%2 == 0 && clickVal[tempN-1] == '*'){ 
                                first = tempN - 1; 
                                clickVal[first] = ' '; 
                                board[first].setText(new String(" " + value[first])); 
                                turn++; 
                        } 
                        else if(turn%2 == 1 && first != tempN-1){ 
                                second = tempN - 1; 
                                clickVal[second] = ' '; 
                                board[second].setText(new String(" " + value[second])); 
                                repaint(); 
                                turn++; 
                                wait(2000);                        //This is where i made my mistake
                                if(value[first] != value[second]){ 
                                        board[first].setText(new String(" " + (first+1))); 
                                        clickVal[first] = '*'; 
                                        board[second].setText(new String(" " + (second+1))); 
                                        clickVal[second] = '*'; 
                                }else{ 
                                        pairs++; 
                                } 
                                if(pairs == 8){ 
                                        message.setText("You win!"); 
                                } 
                        }        
                } 
        } 
 
        static void wait(int n){ 
                long t0,t1; 
                t0=System.currentTimeMillis(); 
                do{ 
                        t1 = System.currentTimeMillis(); 
                } 
                while(t1-t0<n); 
        } 
 
        static void shuffle(char [] a){ 
                int f; 
                int s; 
                char hold; 
                for(int i = 0; i < 100; i++){ 
                        f = (int) (Math.random()*16); 
                        s = (int) (Math.random()*16); 
                        hold = a[f]; 
                        a[f] = a[s]; 
                        a[s] = hold; 
                } 
        } 
}

Was This Post Helpful? 0

#4 gwunta  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 07-September 09

Re: Waiting in Java

Posted 13 May 2010 - 05:47 AM

I think you need something like

thread.sleep(2000)

but its hard to tell unless I see your wait method

The Thread class usually takes care of that sort of thing, but you will most likely need to deal with any exceptions it throws.
Was This Post Helpful? 0
  • +
  • -

#5 Guest_simon*


Reputation:

Re: Waiting in Java

Posted 13 May 2010 - 05:49 AM

the wait method should be at the bottom of the code, but here it is again

        static void wait(int n){ 
                long t0,t1; 
                t0=System.currentTimeMillis(); 
                do{ 
                        t1 = System.currentTimeMillis(); 
                } 
                while(t1-t0<n); 
        } 



and the issue is not that it doesnt wait, its that it waits too soon
Was This Post Helpful? 0

#6 gwunta  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 07-September 09

Re: Waiting in Java

Posted 13 May 2010 - 05:51 AM

Does n need to be a float datatype too??? Im not sure, but it looks like it should work as it is.....
Was This Post Helpful? 0
  • +
  • -

#7 Guest_Simon*


Reputation:

Re: Waiting in Java

Posted 13 May 2010 - 05:56 AM

View Postgwunta, on 13 May 2010 - 04:51 AM, said:

Does n need to be a float datatype too??? Im not sure, but it looks like it should work as it is.....


it does work, but if you try it yourself, you see that it waits before it displays the second button you click on
board[second].setText(new String(" " + value[second]));
				repaint();
				turn++;
				wait(2000);


board[second].setText(new String(" " + value[second]));
looks like it should happen before
wait(2000)
because of the order, but it waits before it sets the text of the button
Was This Post Helpful? 0

#8 gwunta  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 07-September 09

Re: Waiting in Java

Posted 13 May 2010 - 06:31 AM

I dont seem to be having the same problem. when I click on a second tile the first one is turning back into a number, not even giving you a chance to see the second. It looks like its an onclick event type problem
Was This Post Helpful? 0
  • +
  • -

#9 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10821
  • View blog
  • Posts: 40,340
  • Joined: 27-December 08

Re: Waiting in Java

Posted 13 May 2010 - 08:21 AM

@gwunta: Swing is not Thread-safe, so the use of Thread.sleep() should be avoided.

@Simon: I would use a different design. On the second click, I would start() a Swing Timer instead of using wait(). The ActionListener for this Timer should handle checking for pairs, as well as resetting the text for your JButtons. Then, after you finish with the Timer events, stop() the Timer. So all the Button Cliks should so is change the text of the JButton. Also, there is no need to repaint(), as JFrame and JButton handle this. Generally speaking, if you don't override paint() or paintComponent(), there probably isn't the need to invoke repaint().

For more information on Swing Timer, check out the API: http://java.sun.com/...wing/Timer.html
Was This Post Helpful? 1
  • +
  • -

#10 Canownueasy  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 5
  • Joined: 16-April 10

Re: Waiting in Java

Posted 13 May 2010 - 08:36 AM

Use this method.

public void wait(int time) {
    thread.sleep(time);
    System.out.print("Waited for " + time);
}

Was This Post Helpful? -1
  • +
  • -

#11 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10821
  • View blog
  • Posts: 40,340
  • Joined: 27-December 08

Re: Waiting in Java

Posted 13 May 2010 - 08:47 AM

I just explained above, Swing is not Thread-safe, so do not use the Thread class at all when working with Swing. Also, the class is Thread upper-case, not thread lower-case.
Was This Post Helpful? 0
  • +
  • -

#12 gwunta  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 07-September 09

Re: Waiting in Java

Posted 13 May 2010 - 09:44 AM

Thanks for that macosxnerd, I learned something new. I did hear that the Thread class has quite a number of issues and that Java 7 might oversome a lot of these issues.

thanks
Was This Post Helpful? 0
  • +
  • -

#13 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,051
  • Joined: 15-July 08

Re: Waiting in Java

Posted 13 May 2010 - 10:54 AM

Swing is Actually designed to not be Thread Safe as shown in their article here:
http://java.sun.com/...s/threads1.html

For this simple waiting task, definitely do it macosxnerd101's way, but if there is a need for multithreaded tasks, you can look into SwingWorker, which integrates itself with Swings event thread.

http://java.sun.com/...ency/index.html

I demonstrate this in the latter half of my tutorial where I present a loading screen until a large image is loaded and displayed:
http://www.dreaminco...nd-swingworker/
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1