I want to create a simple tic tac toe applet. Below is my code
Questions:
1. For my actionPerformed method. Instead of labelling every button with numbers (1~9) and using getActionCommand to identify which button is clicked, is there other simple way to detect which button has been clicked? So that i need not copy my codes in actionPerformed() 9 times..
2. How do i detect a win/lose/tie? How do i code it?
Code:import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * Simple tic-tac-toe applet. Win/tie status is shown at the top of the * applet. */ public class TicTacToe extends JApplet implements ActionListener { JLabel messagesLabel=new JLabel("X goes first"); JPanel displayPanel=new JPanel(new GridLayout(3,3)); private static int count=0; private static JButton b1=new JButton("1"); private static JButton b2=new JButton("2"); private static JButton b3=new JButton("3"); private static JButton b4=new JButton("4"); private static JButton b5=new JButton("5"); private static JButton b6=new JButton("6"); private static JButton b7=new JButton("7"); private static JButton b8=new JButton("8"); private static JButton b9=new JButton("9"); public void init(){ getContentPane().setLayout(new BorderLayout()); getContentPane().add(messagesLabel, BorderLayout.NORTH); add(displayPanel, BorderLayout.CENTER); b1.addActionListener(this); displayPanel.add(b1); b2.addActionListener(this); displayPanel.add(b2); b3.addActionListener(this); displayPanel.add(b3); b4.addActionListener(this); displayPanel.add(b4); b5.addActionListener(this); displayPanel.add(b5); b6.addActionListener(this); displayPanel.add(b6); b7.addActionListener(this); displayPanel.add(b7); b8.addActionListener(this); displayPanel.add(b8); b9.addActionListener(this); displayPanel.add(b9); getContentPane().add(displayPanel, BorderLayout.CENTER); } public void actionPerformed(ActionEvent e){ String actionCommand=e.getActionCommand(); if(actionCommand=="1"){ if(count==0 ||count%2==0){ b1.setText("X"); count++; }else{ b1.setText("O"); count++; } } if(actionCommand=="2"){ if(count==0 ||count%2==0){ b2.setText("X"); count++; }else{ b2.setText("O"); count++; } } if(actionCommand=="3"){ if(count==0 ||count%2==0){ b3.setText("X"); count++; }else{ b3.setText("O"); count++; } } if(actionCommand=="4"){ if(count==0 ||count%2==0){ b4.setText("X"); count++; }else{ b4.setText("O"); count++; } } if(actionCommand=="5"){ if(count==0 ||count%2==0){ b5.setText("X"); count++; }else{ b5.setText("O"); count++; } } if(actionCommand=="6"){ if(count==0 ||count%2==0){ b6.setText("X"); count++; }else{ b6.setText("O"); count++; } } if(actionCommand=="7"){ if(count==0 ||count%2==0){ b7.setText("X"); count++; }else{ b7.setText("O"); count++; } } if(actionCommand=="8"){ if(count==0 ||count%2==0){ b8.setText("X"); count++; }else{ b8.setText("O"); count++; } } if(actionCommand=="9"){ if(count==0 ||count%2==0){ b9.setText("X"); count++; }else{ b9.setText("O"); count++; } } } }


Reply With Quote


Bookmarks