Advertisement
Guest User

Untitled

a guest
Dec 8th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. import javax.swing.JFrame;
  2. import java.awt.event.ActionListener;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.Font;
  5. import javax.swing.JButton;
  6. import java.awt.GridLayout;
  7.  
  8. public class AdinTicTacToe extends JFrame implements ActionListener {
  9. private static final long serialVersionUID = 1L;
  10. public static final int WIDTH = 500; //Width of the JFrame
  11. public static final int HEIGHT = 400; //Height of the JFrame
  12.  
  13. public static void main(String[] args) {
  14. AdinTicTacToe gui = new AdinTicTacToe(3, 3);
  15. gui.setVisible(true);
  16. }
  17. //Creating a matrix of buttons to make flexible layout
  18. JButton[][] buttons = new JButton[3][3]; {
  19. for(int row=0; row < buttons.length; row++) {
  20. for( int col=0 ; col < buttons[0].length ; col++ ) {
  21. JButton cells = new JButton();
  22. buttons[row][col] = cells;
  23. add(cells);
  24. cells.addActionListener(this);
  25. }
  26. }
  27. }
  28. //A constructor to set initial values
  29. public AdinTicTacToe(int rows, int columns ) {
  30. super();
  31. setSize(WIDTH, HEIGHT);
  32. setTitle("Tic Tac Toe");
  33. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  34.  
  35. //Setting a layout
  36. setLayout(new GridLayout(rows, columns ));
  37. }
  38.  
  39. //Handling button clicks
  40. boolean check; //Variable to determine the current state of a button
  41. @Override
  42. public void actionPerformed(ActionEvent e) {
  43. //Using getSource method to avoid multiple if statements and make it efficient
  44. JButton myButton = (JButton)e.getSource();
  45. if (!check)
  46. myButton.setText("X");; //Set X to the clicked cell
  47. if (check)
  48. myButton.setText("O"); //Set O to the clicked cell
  49. check = !check; //Reverting the button state
  50. myButton.setFont(new Font("Arial", Font.BOLD, 60)); //Set font of X and O
  51. myButton.setEnabled(false); //Disable button after it gets clicked
  52.  
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement