Netbeans IDE Tutorials

And a free Snake game as bonus from PBL

Page 1 of 1

10 Replies - 9005 Views - Last Post: 26 July 2009 - 06:59 PM Rate Topic: -----

#1 mikecheer101  Icon User is offline

  • D.I.C Head

Reputation: -9
  • View blog
  • Posts: 114
  • Joined: 12-June 09

Netbeans IDE Tutorials

Post icon  Posted 16 June 2009 - 12:55 PM

does anyone know where i can find a tutorial for Netbeans game making?
ive searched google already and cant find anything on it B)

This post has been edited by pbl: 16 June 2009 - 09:01 PM

Is This A Good Question/Topic? 0
  • +

Replies To: Netbeans IDE Tutorials

#2 Nykc  Icon User is offline

  • Gentleman of Leisure
  • member icon

Reputation: 725
  • View blog
  • Posts: 8,638
  • Joined: 14-September 07

Re: Netbeans IDE Tutorials

Posted 16 June 2009 - 01:21 PM

The very first result in Google gave this really informative link.

http://wiki.netbeans...WithGameBuilder

edit - here is another

http://wiki.netbeans...sicGameTemplate

This post has been edited by Nykc: 16 June 2009 - 01:23 PM

Was This Post Helpful? 0
  • +
  • -

#3 mikecheer101  Icon User is offline

  • D.I.C Head

Reputation: -9
  • View blog
  • Posts: 114
  • Joined: 12-June 09

Re: Netbeans IDE Tutorials

Posted 16 June 2009 - 06:03 PM

o thoughs tutorials didnt help at all because i have a newer version.anybody else kno any netbean gamemaking java tutorials?
Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: Netbeans IDE Tutorials

Posted 16 June 2009 - 06:45 PM

View Postmikecheer101, on 16 Jun, 2009 - 05:03 PM, said:

o thoughs tutorials didnt help at all because i have a newer version.anybody else kno any netbean gamemaking java tutorials?

Netbeans is just an IDE.. a fancy editor, do not search for "NetBeans game making" search for "Java game making"
making a game is Java can be done through Notepad, Eclipse, JBuilder,...
it is like if you were looking for "using the clutch on a Ford"... you actually want "using a cluth in a car" dont care if its is Ford, GM, Toyota, ....

Notepad, Netbeans, Eclipse, JFrame, JBuilder are model of car
you just one to learn how to drive a vehicle
Was This Post Helpful? 0
  • +
  • -

#5 Fuzzyness  Icon User is offline

  • Comp Sci Student
  • member icon

Reputation: 669
  • View blog
  • Posts: 2,438
  • Joined: 06-March 09

Re: Netbeans IDE Tutorials

Posted 16 June 2009 - 06:45 PM

You really need to start with basics. I would love to go start making games but if you dont know how then you cant. Start with the basics of Java and work way to games. Google is your friend in Tutorial finding. They have tutorials for the "new" NetBeans, just look them up.

You should really stop making multiple forums asking for tutorials/codes when all you need to do is go to google and search them.

Google
Sun Java Tutorials

Goodluck

This post has been edited by Fuzzyness: 16 June 2009 - 06:47 PM

Was This Post Helpful? 0
  • +
  • -

#6 jcmaster2  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 183
  • Joined: 27-April 09

Re: Netbeans IDE Tutorials

Posted 16 June 2009 - 08:03 PM

You seem do not take the hint that you are likely trying to do more than you can handle..

And you think learning a language and creating a game is *easy*

If you are not sure why don't you use something like:

Gamemaker:

http://www.yoyogames.com/make

or

The Games Factory 2

http://www.clickteam.com/eng/tgf2.php

Easy to create games without much programming...


Seriously- take the hints that have be given to you :crazy:
Was This Post Helpful? 0
  • +
  • -

#7 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: Netbeans IDE Tutorials

Posted 16 June 2009 - 09:01 PM

Nothing to do tonigh... the forum is quiet

Here is your first game a very simple one written in 15 minutes... not pretty good code
you can test it and play with it

The basic snake game
the snake crawls.. if it is the border you are dead
if it hist itself you are dead
if it eats food (the red sqare) it growths and go faster

you can change the dirction the snake crawls by clicking a case to the left/right of it if it goes vertically or over/iunder its head if it foes horizontally

You can "pause" if you want to rest
Enjoy

import javax.swing.*;
import java.awt.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.*;

public class Snake extends JFrame implements Runnable, ActionListener {

	// number of squares in the grid, size of each of them
	private static final int SIZE = 25, WIDTH = 20;
	// the labels for displaying the snake and its foods
	private SnakeLabel[][] label = new SnakeLabel[SIZE][SIZE];
	// arrayList containing all of the snake position (Labels)
	private SnakeList snakeList = new SnakeList();
	// the label displaying if I am running or not and the size of the snake
	private JLabel statusLabel = new JLabel();
	// random number generator to find a new spot for a new food when I eat one
	private Random random = new Random();
	// if I am in a pause state or not
	boolean pause = false;
	// the button to switch from pause to not pause
	private JButton pauseResume = new JButton("Pause");
	// which direction I am running and where is my head
	private int directionX = 0, directionY = -1, headX, headY;
	
	Snake() {
		super("Snake Game");
		// to hold all the labels
		JPanel panel = new JPanel(new GridLayout(SIZE, SIZE, 1, 1));
		panel.setBackground(Color.BLUE);
		panel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
		// create all the JLabel
		for(int j = 0; j < SIZE; j++) {
			for(int i = 0; i < SIZE; i++) {
				label[i][j] = new SnakeLabel(i, j);
				panel.add(label[i][j]);
			}
		}
		
		// add the 4 foods
		initFood();
		// the snake in the middle of everything initial size 8
		headX = SIZE / 2;
		headY = (SIZE / 2) - 4;
		// declare these label as holding the snake
		// registering them in the arrayList
		for(int i = 0; i < 8; i++)
			snakeList.addLabel(label[headX][headY + i]);
		
		add(panel, BorderLayout.CENTER);
		// label if I am running well and size of the snake
		statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
		add(statusLabel, BorderLayout.NORTH);
		// listener so the pause button will work
		pauseResume.addActionListener(this);
		add(pauseResume, BorderLayout.SOUTH);
		// general JFrame stuff its size and visible
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setSize(SIZE * WIDTH, SIZE * WIDTH);
		setVisible(true);
		Thread thread = new Thread(this);
		thread.start();
	}
	
	// to put the initial 4 food labels in 1/4 of the grid
	private void initFood() {
		// north/west at 1/4 of the grid
		int x = SIZE / 4;
		int y = x;
		label[x][y].setFood(true);
		// north east so x is the same delta from the end
		x = SIZE - x;
		label[x][y].setFood(true);
		// south/west
		y = x;
		x = SIZE / 4;
		label[x][y].setFood(true);
		// south east
		x = y;
		label[x][y].setFood(true);		
	}
	// run as a thread to move the snake
	public void run() {
		for(;;) {
			// wait according to snake length... determine an empiric way
			try {
				Thread.sleep(10000L / snakeList.size());
			}
			catch(Exception e) {}
			// if the "Pause" button was pushed go to next turn
			if(pause)
				continue;
			// update snake head position
			headX += directionX;
			headY += directionY;
			// check if we are going out of bound
			if(headX < 0 || headX >= SIZE || headY < 0 || headY >= SIZE) {
				statusLabel.setText("Out of bound... length: " + snakeList.size());
				return;
			}
			// check if we are eating ourself
			if(label[headX][headY].isSnake) {
				statusLabel.setText("You eat yourself... length: " + snakeList.size());
				return;
			}
			// if we hit food
			if(label[headX][headY].isFood) {
				snakeList.updateHead();	 // without updating tail
				// found new place for food
				for(;;) {
					int x = random.nextInt(SIZE);
					int y = random.nextInt(SIZE);
					// start again if new random place is already in the snake or is already food
					if(label[x][y].isFood)
						continue;
					if(label[x][y].isSnake)
						continue;
					// ok good dpot not used yet/// declare it as food
					label[x][y].setFood(true);
					break;
				}
			}
			else {
				snakeList.updateTail();	 // first if I pass on my back
				snakeList.updateHead();
			}
			statusLabel.setText("Running... snake length: " + snakeList.size());
		}
	}
	// called when the pause/resume button is hit
	public void actionPerformed(ActionEvent e) {
		// change the state
		pause = !pause;
		// updtae button text accordingly
		if(pause)
			pauseResume.setText("Resume");
		else
			pauseResume.setText("Pause");
	}
	// to run the whole damned thing
	public static void main(String[] args) {

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new Snake();
			}
		});
	}
	// arrtay list that contains the position taken by the snake
	class SnakeList extends ArrayList<SnakeLabel> {
		
		// for initial build when we install the snake first positions
		boolean addLabel(SnakeLabel sl) {
			sl.setSnake(true);
			return super.add(sl);
		}
		// remove (make free) the tail of the snake
		void updateTail() {
			SnakeLabel sl = remove(size() - 1);
			sl.setSnake(false);
		}
		// to update the head to new position
		void updateHead() {
			label[headX][headY].setSnake(true);
			add(0, label[headX][headY]);
		}
	}
	// extends JLabel to keep coordinate X and Y and have a mouseListener if cliked
	class SnakeLabel extends JLabel implements MouseListener{
		private int x, y;
		// init not food not snake
		boolean isFood = false;
		boolean isSnake = false;
		// constructor
		SnakeLabel(int x, int y) {
			super("");
			// save my coordinates
			this.x = x; this.y = y;
			// opaque because I use background to represent myself
			setOpaque(true);
			// so I will react if I am cleicked
			addMouseListener(this);
			// default color
			setBackground(Color.WHITE);
		}
		// declares me as a food case or not
		void setFood(boolean state) {
			isFood = state;
			// change color accordingly
			if(state)
				setBackground(Color.RED);
			else
				setBackground(Color.WHITE);
		}
		// declares me as part of the snake or not
		void setSnake(boolean state) {
			isSnake = state;
			// change my color accordingly
			if(state) {
				setBackground(Color.BLUE);
				isFood = false;	  // slot availabel again if I just eat it for later use
			}
			else {
				setBackground(Color.WHITE);
			}
		}
		// ok click on me
		public void mouseClicked(MouseEvent e) {
			// so am I going vertically or horitonaly
			if(directionX == 0) {
				// if clicked to my left
				if(x < headX) {
					// update the way I am going
					directionX = -1;
					directionY = 0;
				}	
				else if(x > headX) {   // is it to my rioght ?
					directionX = +1;
					directionY = 0;					
				}
			}
			else {				  // OK I am moving horizontaly
				if(y < headY) {	 // to my left
					directionY = -1;
					directionX = 0;
				}
				if(y > headY) {	 // to my right ?
					directionY = +1;
					directionX = 0;
				}
				
			}
		}
		// do not react to those
		public void mouseEntered(MouseEvent arg0) {
		}
		public void mouseExited(MouseEvent arg0) {
		}
		public void mousePressed(MouseEvent arg0) {
		}
		public void mouseReleased(MouseEvent arg0) {
		}
		
	}
}



This post has been edited by pbl: 17 June 2009 - 04:48 PM

Was This Post Helpful? 0
  • +
  • -

#8 333OnlyHalfEvil  Icon User is offline

  • D.I.C Addict

Reputation: 24
  • View blog
  • Posts: 664
  • Joined: 20-March 09

Re: Netbeans IDE Tutorials

Posted 16 June 2009 - 09:37 PM

Awesome
Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: Netbeans IDE Tutorials

Posted 16 June 2009 - 09:39 PM

View Post333OnlyHalfEvil, on 16 Jun, 2009 - 08:37 PM, said:

Awesome

Thanks enjoy :D
Though of it in the car coming back from the office... thinking also about your problem and how to explain it
Was This Post Helpful? 0
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: Netbeans IDE Tutorials

Posted 17 June 2009 - 08:48 PM

Here is a nicer version with more gagdets
I still havbe to add a level of difficulty Slider

import javax.swing.*;
import java.awt.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.*;

public class Snake extends JFrame implements Runnable, ActionListener {

	private static final long serialVersionUID = 123654L;   // just to avoid compile warning
	// number of squares in the grid, size of each of them
	private static final int SIZE = 25, WIDTH = 20;
	// the labels for displaying the snake and its foods
	private SnakeLabel[][] label = new SnakeLabel[SIZE][SIZE];
	// arrayList containing all of the snake position (Labels)
	private SnakeList snakeList = new SnakeList();
	// the label displaying if I am running or not and the size of the snake
	private JLabel statusLabel = new JLabel("Initializing");
	// random number generator to find a new spot for a new food when I eat one
	private Random random = new Random();
	// if I am in a pause state or not
	boolean pause = false;
	// the button to switch from pause to not pause
	private JButton pauseResume = new JButton("Pause");
	// which direction I am running and where is my head
	private int directionX = 0, directionY = -1, headX, headY;
	// the refresh rate
	private long refreshRate;

	Snake() {
		super("Snake Game");
		// to hold all the labels with a gap of 1 pixel
		JPanel panel = new JPanel(new GridLayout(SIZE, SIZE, 1, 1));
		// the same color as the Snake so the back will show a continuos snake
		panel.setBackground(Color.BLUE);
		panel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
		// create all the JLabels
		initLabels(panel);
		
		// add the 4 foods
		initFood();
		// init the snake the length of a quarter of our size
		initSnake(SIZE / 4);
		add(panel, BorderLayout.CENTER);
		
		// label if I am running well and size of the snake
		statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
		statusLabel.setOpaque(true);
		statusLabel.setBackground(Color.YELLOW);
		add(statusLabel, BorderLayout.NORTH);
		// listener so the pause button will work
		pauseResume.setForeground(Color.RED);
		pauseResume.addActionListener(this);
		add(pauseResume, BorderLayout.SOUTH);
		// general JFrame stuff its size and visible
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setSize(SIZE * WIDTH - 5, SIZE * WIDTH - 5);
		setVisible(true);
		// start the thread that move the snakes
		Thread thread = new Thread(this);
		thread.start();
	}
	
	// to initialize the labels filling the grid
	// this method is called only once
	private void initLabels(JPanel p) {
		for(int j = 0; j < SIZE; j++) {
			for(int i = 0; i < SIZE; i++) {
				label[i][j] = new SnakeLabel(i, j);
				p.add(label[i][j]);
			}
		}
		
	}
	// to put the initial 4 food labels in 1/4 of the grid
	// this method will be called only once
	private void initFood() {
		// north/west at 1/4 of the grid
		int x = SIZE / 4;
		int y = x;
		label[x][y].setFood(true);
		// north east so x is the same delta from the end
		x = SIZE - x;
		label[x][y].setFood(true);
		// south/west
		y = x;
		x = SIZE / 4;
		label[x][y].setFood(true);
		// south east
		x = y;
		label[x][y].setFood(true);		
	}
	
	// to position the snake at the beginning of game
	private void initSnake(int length) {
		// the snake in the middle of everything initial size of length
		headX = SIZE / 2;
		headY = (SIZE / 2) - (length / 2);
		// declare these label as holding the snake
		// registering them in the arrayList
		for(int i = headY; i < headY + length; i++)
			snakeList.addLabel(label[headX][i]);
		// set the color for the first time
		snakeList.updateColor();
	}
		
	// run as a thread to move the snake
	public void run() {
		for(;;) {
			// wait according to snake length... determine an empiric way
			refreshRate = 5000L / (snakeList.size() / 2);
			// manage to have at least a minimum refresh rate
			if(refreshRate < 10L)
				refreshRate = 10L;
			
			try {
				Thread.sleep(refreshRate);
			}
			catch(Exception e) {}
			// if the "Pause" button was pushed go to next turn
			if(pause)
				continue;
			// update snake head position
			headX += directionX;
			headY += directionY;
			// check if we are going out of bound
			if(headX < 0 || headX >= SIZE || headY < 0 || headY >= SIZE) {
				statusLabel.setText("Out of bound... length: " + snakeList.size());
				return;
			}
			// check if we are eating ourself
			if(label[headX][headY].isSnake) {
				statusLabel.setText("You eat yourself... length: " + snakeList.size());
				return;
			}
			// if we hit food
			if(label[headX][headY].isFood) {
				snakeList.updateHead();	 // without updating tail
				// found new place for food
				for(;;) {
					int x = random.nextInt(SIZE);
					int y = random.nextInt(SIZE);
					// start again if new random place is already in the snake or is already food
					if(label[x][y].isFood)
						continue;
					if(label[x][y].isSnake)
						continue;
					// ok good dpot not used yet/// declare it as food
					label[x][y].setFood(true);
					break;
				}
			}
			else {
				snakeList.updateTail();	 // first if I pass on my back
				snakeList.updateHead();
			}
			statusLabel.setText("Running... snake length: " + snakeList.size() 
											+ "	Refresh Rate: " + refreshRate + "/1000 sec");
		}
	}
	// called when the pause/resume button is hit
	public void actionPerformed(ActionEvent e) {
		// change the state
		pause = !pause;
		// updtae button text accordingly
		if(pause)
			pauseResume.setText("Resume");
		else
			pauseResume.setText("Pause");
	}
	// to run the whole damned thing
	public static void main(String[] args) {

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new Snake();
			}
		});
	}
	// array list that contains the position taken by the snake
	private class SnakeList extends ArrayList<SnakeLabel> {
		private static final long serialVersionUID = 654321L;  // to avoid compile warning
		// the 2 colours of the snake
		private Color[] snakeColor = {new Color(0, 0, 255), new Color(75, 75, 255)};
		// for initial build when we install the snake first positions
		private boolean addLabel(SnakeLabel sl) {
			// flag the SnakeLabel as being part of the Snake
			sl.setSnake(true);
			// call father's method to add an object into the arrayList
			return add(sl);
		}
		// remove (make free) the tail of the snake
		private void updateTail() {
			SnakeLabel sl = remove(size() - 1);
			sl.setSnake(false);
		}
		// to update the head to new position
		private void updateHead() {
			// declare it as part of the snake
			label[headX][headY].setSnake(true);
			// add it to the head of the snake
			add(0, label[headX][headY]);
			// switch colors
			updateColor();
		}
		
		// to put 2 colours in the snake
		private void updateColor() {
			int len = size();
			// the head in black
			get(0).setBackground(Color.BLACK);
			// variation of blue for the others
			for(int i = 1; i < len; i++) {
				get(i).setBackground(snakeColor[i % snakeColor.length]);
			}
		}
	} // end of inner class SnakeList
	
	// specialized JLabel to keep coordinate X and Y and have a mouseListener if cliked
	private class SnakeLabel extends JLabel implements MouseListener{
		private static final long serialVersionUID = 123456L;   // to avoid compile warning
		// my coordinates on the Grid so the mouseListener can know where I am situate
		private int x, y;
		// init not food and not snake
		boolean isFood = false;		 // not a food case
		boolean isSnake = false;		// not part of the snake
		// constructor
		SnakeLabel(int x, int y) {
			super("");
			// save my coordinates
			this.x = x; this.y = y;
			// opaque because I use background to represent myself
			setOpaque(true);
			// so I will react if I am cleicked
			addMouseListener(this);
			// default color
			setBackground(Color.WHITE);
		}
		// declares me as a food case or not
		private void setFood(boolean state) {
			isFood = state;
			// change color accordingly
			if(state)
				setBackground(Color.RED);	   // food color
			else
				setBackground(Color.WHITE);	 // regular color
		}
		// declares me as part of the snake or not
		private void setSnake(boolean state) {
			isSnake = state;
			// change my color accordingly
			if(state) {
				setFood(false);	  // make it available again as food slot
				setBackground(Color.BLUE);
			}
			else {
				setBackground(Color.WHITE);
			}
		}
		
		// ok click on me I just chek for the Pressed event to react faster
		// (important when the snake goes very fast)
		public void mousePressed(MouseEvent e) {
			// so am I going vertically or horitonaly
			if(directionX == 0) {
				// if clicked on my same X nothing to do
				if(x == headX)
					return;
				directionY = 0;				// stop updating Y
				// if clicked to my left
				if(x < headX) {
					// update the way I am going
					directionX = -1;
				}	
				else  {   // so to my rioght
					directionX = +1;				
				}
			}
			else {				  // OK I am moving horizontaly
				if(y == headY)
					return;
				directionX = 0;
				if(y < headY) {	 // to my left
					directionY = -1;
				}
				else {	 // to my right
					directionY = +1;
				}				
			}
		}
		// do not react to those but as I implement MouseListener have have to implement these
		public void mouseEntered(MouseEvent arg0) {}
		public void mouseExited(MouseEvent arg0) {}
		public void mouseClicked(MouseEvent arg0) {}
		public void mouseReleased(MouseEvent arg0) {}
		
	}  // end inner class SnakeLabel
}


Was This Post Helpful? 1
  • +
  • -

#11 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: Netbeans IDE Tutorials

Posted 26 July 2009 - 06:59 PM

Here is a simple MemoryGame
import java.awt.*;
import java.awt.event.*;
import java.util.*;			// for Random and ArrayList

import javax.swing.*;		// obviously a lot of swing
import javax.swing.event.MouseInputListener;

/*
 * You can't imagine how many post in the forum request for ready to go Game
 * I saw that one on the net yesterday so decide to spend an hour or 2 to write in Java
 * I didn't make a tutorial out of it... no time to do so but here for fun
 * A little trivia game
 * a few numbers from 0 to 9 circled by circle are showed a few seconds
 * then the value disappear and only the circles are displayed
 * You have then to click on the circles in order of the numbers that where shown
 */
public class GuessWhereAreTheNumbers extends JFrame implements Runnable, ActionListener {
	// number of rows and colums
	private static final int NB_ROWS = 5, NB_COLS = 7;
	// the labels that will represent sometimes a number sometimes a circle
	private CircleLabel[][] label = new CircleLabel[NB_ROWS][NB_COLS];
	// a Random object to determine the displayed numbers and their location
	private Random random = new Random();
	// the panel that hold the radio button and the button
	private BottomPanel bottomPanel;
	// the Button to start a game
	private JButton button = new JButton("Go !");
	// the label at the top to say if you win or fail
	private JLabel statusLabel = new JLabel("\n");
	// the array of the labels in the game (the ones that hold a number from 0 to 9)
	private CircleLabel[] cl;
	// the number of labels correctly clicked
	private int nbClicked;
	
	GuessWhereAreTheNumbers() {
		super("Guess where are the numbers");
		setBackground(Color.WHITE);
		// the status label at the top
		statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
		// just fancy color stuff
		statusLabel.setForeground(Color.BLUE);
		statusLabel.setBackground(Color.YELLOW);
		statusLabel.setForeground(Color.RED);
		// posted at the top of the JFrame
		add(statusLabel, BorderLayout.NORTH);
		// a JPanel with a grid to display all my labels
		JPanel panel = new JPanel(new GridLayout(NB_ROWS, NB_COLS));
		panel.setBackground(Color.WHITE);
		// put our labels into it
		for(int j = 0; j < NB_COLS; j++) {
			for(int i = 0; i < NB_ROWS; i++) {
				label[i][j] = new CircleLabel(i, j);
				panel.add(label[i][j]);
			}
		}
		// add the JPanel to the main frame
		add(panel, BorderLayout.CENTER);
		// the BottomPanel that holds the RadioButtons and the Button Go
		bottomPanel = new BottomPanel(this);
		// put it south
		add(bottomPanel, BorderLayout.SOUTH);
		// set size (a little more pixel on the Y axis for bottom and top panel) and default close operation
		setSize(NB_COLS * 50, NB_ROWS * 50 + 20);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setVisible(true);
		
	}
	
	// the thread that actually display the numbers and then hides them
	public void run() {
		// while the game runs make the button "GO" unavailable
		button.setEnabled(false);
		// number of label clicked
		nbClicked = 0;
		// erase the status label from the last game
		statusLabel.setText("\n");
		// fill an ArrayList with all the available labels so we can picj them randomly
		ArrayList<CircleLabel> al = new ArrayList<CircleLabel>();
		for(int j = 0; j < NB_COLS; j++) {
			for(int i = 0; i < NB_ROWS; i++) {
				// reset label no text to display no circle to draw
				label[i][j].setValue(-1);
				// add to the arrayList
				al.add(label[i][j]);
			}
		}
		// get the number of numbers/circles to display (depending of the JButton selected in the bottomPanel)
		int nbToShow = bottomPanel.getNbCircle();
		// an array of the labels which will be displayed
		cl = new CircleLabel[nbToShow];
		// another ArrayList to determine the value that will be shown in the label
		ArrayList<Integer> oneToNine = new ArrayList<Integer>();
		for(int i = 0; i <= 9; i++)
			oneToNine.add(i);
		// pickup randomly nbToShow labels
		for(int i = 0; i < nbToShow; i++) {
			cl[i] = al.remove(random.nextInt(al.size()));
			// get a random value for it
			int val = oneToNine.remove(random.nextInt(oneToNine.size()));
			// set these value to the label
			cl[i].setValue(val);
		}
		// wait for the user to remember the number
		try {
			Thread.sleep(1500L);	// this is 1.5 second you can change it
		}
		catch (Exception e) {
			throw new IllegalStateException("Thread.Sleep() failed for " + e);
		}
		// now display the circle only
		for(int i = 0; i < nbToShow; i++) {
			cl[i].setCircleOnly();
		}
		// sort the labels by their values so I can check if they are clicked in the good order
		Arrays.sort(cl);
	}
	
	// we'll be called when the button "GO" will be clicked
	public void actionPerformed(ActionEvent e) {
		Thread thread = new Thread(this);
		thread.start();
	}
	// just to start the application
	public static void main(String[] args) {

		// one instance of our stuff
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new GuessWhereAreTheNumbers();
			}
		});
	}
	
	// a special version of JLabel. It can display a number or a circle or an X or nothing
	// it has a mouseInputListener and implements Comparable so they can be sorted in order of Value
	class CircleLabel extends JLabel implements MouseInputListener, Comparable<CircleLabel> {
		// tne number it holds (-1) in no value
		int value;
		// the String representation of the number to display
		String valueToDisplay = "";
		// if I should display the X wrong answer
		boolean displayX = false;
		// my coordinates within the Panel
		int x, y;
		
		// constructor
		CircleLabel(int x, int y) {
			// init at nothing
			super("");
			// save position on grid
			this.x = x;
			this.y = y;
			// do not display the X
			displayX = false;
			// no value
			valueToDisplay = "";
			value = -1;
			this.setHorizontalAlignment(SwingConstants.CENTER);
			// and the mouse listener
			this.addMouseListener(this);
		}
		// to set the value of the label
		void setValue(int val) {
			// value in int
			value = val;
			// special case when value is -1
			if(value == -1)
			{			
				valueToDisplay = "";	// don't display any number
			}
			else {				
				// as a String so repaint can use it
				valueToDisplay = "" + val;
			}
			setText(valueToDisplay);		// value used by repaint
			displayX = false;				// init we do not display an X over the label
			// set foreground value to BLUE in case last game set it to RED
			setForeground(Color.BLUE);
		}

		// now display only circle
		void setCircleOnly() {
			// text reset to nothing
			setText("");
		}
		
		// the paint method: we overload the standard one in case we have to draw an X
		public void paint(Graphics g) {
			// always call my father in case I have text to display
			super.paint(g);
			// if an empty label, not selected for that game I exit
			if(value == -1)
				return;
			// draw a circle around it
			// get size of label
			Dimension dim = getSize();
			// get size of circle 1/6 of label size
			int width = dim.width / 6;
			int height = dim.height / 6;
			// draw the circle in black
			g.setColor(Color.BLACK);
			g.drawOval(width, height, width * 5, height * 5);	
			// test if we have to display the X
			if(displayX) {
				// OK just another color to be fancier
				g.setColor(Color.GREEN);
				// from the leftmost uppercorner to rightmost lower corner
				g.drawLine(0, 0, dim.width, dim.height);
				// from rightmost upper corner to leftmost lower corner
				g.drawLine(dim.width, 0, 0, dim.height);
			}
		}
		
		// the only listener I really use
		@Override
		public void mouseClicked(MouseEvent e) {
			// if we click on a label that does not have a value ignore it
			if(value == -1)
				return;
			// validate that I am the good label
			if(cl[nbClicked].value == value) {
				// remove the circle and display the bumber
				setText(valueToDisplay);
				// ok we will check the next one
				nbClicked++;
				// check if we are done
				if(nbClicked == cl.length) {
					statusLabel.setText("You win\n");
					// ok ready to start a new game
					button.setEnabled(true);
				}
				else {
					statusLabel.setText("" + nbClicked + " out of " + cl.length + " done.");
				}
					
			}
			else {				// bad click
				statusLabel.setText("You loose\n");
				// display the values of the selected label this is done by setting them to their values
				// the method will reset valueToDisplay
				for(int i = 0; i < cl.length; i++) {
					cl[i].setValue(cl[i].value);
				}
				// have the culprit label to have an X over it and display it's number in red
				badChoice();
				// ok ready to start a new game
				button.setEnabled(true);
			}	
		}
		
		// use to say that it should 1) display an X 2) display the value in red
		void badChoice() {
			displayX = true;			// flag next repaint will have to paint the X
			setForeground(Color.RED);	// and the culprit will display it's value in RED
		}

		// unused MouseListener methods
		public void mouseEntered(MouseEvent e) {}
		public void mouseExited(MouseEvent e) {}
		public void mousePressed(MouseEvent e) {}
		public void mouseReleased(MouseEvent e) {}
		public void mouseDragged(MouseEvent arg0) {}
		public void mouseMoved(MouseEvent arg0) {}
		
		// a compareTo method to sort the label according to their instance variable value
		public int compareTo(CircleLabel otherCircleLabel) {
			// just return if < or > to the one we compare
			return value - otherCircleLabel.value;
		}	
	}
	
	// the panel that will be put South to select number of Circle to display and the go button
	class BottomPanel extends JPanel {
		// 3 radio buttons for 4, 5, 6 circles
		JRadioButton[] radio = new JRadioButton[3];
		
		// Constructor receives as parameter our JFrame which is the listener
		BottomPanel(ActionListener al) {
			// 1 row and 5 columns: the title, 3 radio, the button, and empty label
			super(new GridLayout(1,6));
			// add a background color
			setBackground(Color.YELLOW);
			// add a label to explain what the RadioButtons are for
			add(new JLabel("Nb Circles:"));
			// a buttonGroup so only 1 radio can be selected at the same time
			ButtonGroup bg = new ButtonGroup();
			// add our RadioButton
			for(int i = 0; i < radio.length; i++) {
				// label of Radio index + 4
				radio[i] = new JRadioButton("" + (i+4));
				radio[i].setBackground(Color.YELLOW);
				// add RadioButton to the group and then to the panel
				bg.add(radio[i]);
				add(radio[i]);
			}
			// make the firt one selected
			radio[0].setSelected(true);
			// add the button
			button.addActionListener(al);
			add(button);	
			// an empty label
			add(new JLabel(""));
		}
		
		// returns the number of circles to draw depending of the JRadioButton selected
		int getNbCircle() {
			// loop to see which JRadioButton is selected
			for(int i = 0; i < radio.length; i++) {
				if(radio[i].isSelected()) {
					return i+4;
				}
			}
			// should not happen but Java compiler wants the method to return an int
			// unless we throw an exception
			throw new IllegalStateException("No Radio selected ???");
		}
		
	}
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1