OCJP

GridLayout Example Program in Java (TicTacToe Game)

As we have discussed Flowlayout in our previous post. During this post we are going to explain GridLayout in AWT. For the same we have used an example of basic game TicTacToe.

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

import javax.swing.JOptionPane;

class MyTictac extends Frame
{
	Button[] btn= new Button[9];
	
	/*
	 * 0 1 2
	 * 3 4 5
	 * 6 7 8
	 */
	Boolean bl= true;
	MyTictac() {
		
		setLayout(new GridLayout(3,3));
		for(int i=0;i<btn.length;i++) {
			
			btn[i]= new Button("");
			add(btn[i]);
			
			btn[i].addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					
					Button bt=(Button)e.getSource();
					
					if(bl) 
					{
						bt.setLabel("O");
					}
					else
					{
					bt.setLabel("X");
					}
					
					bt.setEnabled(false);
					bl= !bl;
				
					if(checkWin()) {
						JOptionPane.showMessageDialog(MyTictac.this, "Game Over");
						System.exit(0);
					}
			
					else
					{
						int cnt=0;
						for(int i=0;i<btn.length;i++) {
							if(btn[i].getLabel()!="") {
								cnt++;
							}
						}
						
						if(cnt==9) {
							JOptionPane.showMessageDialog(MyTictac.this, "Game Draw");
							System.exit(0);
						}
					}
				}
			});
		}
	}
	
	
	public Boolean checkWin()
	{
		Boolean ans =false;
		
if(btn[0].getLabel()!="" && btn[0].getLabel()== btn[1].getLabel() && btn[1].getLabel() == btn[2].getLabel())
{
	return true;
}
else if(btn[3].getLabel()!="" && btn[3].getLabel()== btn[4].getLabel() && btn[4].getLabel() == btn[5].getLabel())
{
	return true;
}
else if(btn[6].getLabel()!="" && btn[6].getLabel()== btn[7].getLabel() && btn[7].getLabel() == btn[8].getLabel())
{
	return true;
}

else if(btn[0].getLabel()!="" && btn[0].getLabel()== btn[3].getLabel() && btn[3].getLabel() == btn[6].getLabel())
{
	return true;
}

else if(btn[1].getLabel()!="" && btn[1].getLabel()== btn[4].getLabel() && btn[4].getLabel() == btn[7].getLabel())
{
	return true;
}

else if(btn[2].getLabel()!="" && btn[2].getLabel()== btn[5].getLabel() && btn[5].getLabel() == btn[8].getLabel())
{
	return true;
}

else if(btn[0].getLabel()!="" && btn[0].getLabel()== btn[4].getLabel() && 
btn[4].getLabel() == btn[8].getLabel())
{
	return true;
}

else if(btn[2].getLabel()!="" && btn[2].getLabel()== btn[4].getLabel() && btn[2].getLabel() == btn[6].getLabel())
{
	return true;
}


		
		return false;
			
	}
}
public class GridDemo {

	
	public static void main(String []a) {
		MyTictac M= new MyTictac();
		
		M.setSize(300,300);
		M.setVisible(true);
	}
}

For more details you can also refer official documents from Oracle https://docs.oracle.com/javase/7/docs/api/java/awt/GridLayout.html

Leave a Reply

Your email address will not be published. Required fields are marked *


× How can I help you?