13 Replies - 1058 Views - Last Post: 16 June 2013 - 05:04 PM Rate Topic: -----

#1 zulfikar2  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 12-June 13

Tic-Tac-Toe[GUI]: score window errors

Posted 12 June 2013 - 03:51 PM

Hi, im zulfikar and this is this project I'm doing alone for school. It is a tic-tac-toe game with a GUI. I've been trying a lot of things with little edits to debug it and have gotten this far learning from google and other sources, but now even those ran out of information i could understand sufficiently to use it in my code.

My main :
import javax.swing.*;
import java.awt.*;
public class game {
  static int height = 0;
  static int width = 0;
  public static void main(String[] args) {
    window win = new window();
    win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    height = 500;
    width = 500;
    win.setSize(width, height);
    win.setLocationRelativeTo(null);
    win.setVisible(true);
    win.setResizable(false);
    win.setForeground(Color.RED);
    win.setBackground(Color.BLACK);
    score sc = new score(win);
    sc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    sc.setSize(width-100, height-100);
    sc.setVisible(true);
    sc.setResizable(false);
    sc.setForeground(Color.RED);
    sc.setBackground(Color.BLACK);
  }
}


My everytime else file :

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class window extends JFrame {
  private final GridLayout grid = new GridLayout(3,3);
  private JLabel player;
  private String players[] = new String[1]; //array with player names
  private String OriP[] = new String[1]; //array with player names original
  private int pcheck = 1; //Mod 2 to get even guy turn
  private JButton squares[] = new JButton[9];
  private JPanel play, holder;
  private String buttext = "O";
  private int d = 0;//draw count 
  private int p1 = 0;//player 1 points
  private int p2 = 0;//player 2 points
  private int pscore[] = new int[1]; //array with player's score
  private String winner = "";//The winner at end
  private String pcount = "";
  private String winguy = "";
  java.util.List s = new ArrayList();
  public window(){ 
    //Title
    super("Tic-Tac-Toe     By : Zulfikar Yusufali");
    pcount = JOptionPane.showInputDialog(null, "How many players are playing?", "Players", JOptionPane.QUESTION_MESSAGE); 
    players(Integer.parseInt(pcount));
    playboard();
    holder();
    add(play);
    copyPList();
    playerShuffle();
    player = new JLabel(players[0] + " it is your turn.");
    player.setForeground(Color.RED);
    add(player, BorderLayout.SOUTH);
  }
  public void players(int p) {
    players = new String[p];
    pscore = new int[p];
    OriP = new String[p];
    for (int x = 0; x < p; x++) {
      players[x] = JOptionPane.showInputDialog(null,"What is your name?","Player " + (x+1), JOptionPane.QUESTION_MESSAGE);
    }
  }
  public void playboard() {
    play = new JPanel();
    play.setLayout(grid);
    //adds the buttons and all the properties for it
    for (int y = 0; y<9; y++) {
      squares[y] = new JButton("");
      squares[y].setFont(new Font(Font.SERIF, 0, 50));
      squares[y].setForeground(Color.RED);
      squares[y].setBackground(Color.BLACK);
      play.add(squares[y]);
      squares[y].addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent z) {
          pcheck++;
          //checks whos turn it is
          if (pcheck%2 == 0) {
            player.setText(players[1] + " it is your turn");
            buttext = "X";
          }
          else {
            player.setText(players[0] + " it is your turn");
            buttext = "O";
          }
          //actionListener for all button press events
          if (z.getSource() == squares[0]) {
            squares[0].setEnabled(false);
            squares[0].setText(buttext);
          }
          else if (z.getSource() == squares[1]) {
            squares[1].setEnabled(false);
            squares[1].setText(buttext);
          }
          else if (z.getSource() == squares[2]) {
            squares[2].setEnabled(false);
            squares[2].setText(buttext);
          }
          else if (z.getSource() == squares[3]) {
            squares[3].setEnabled(false);
            squares[3].setText(buttext);
          }
          else if (z.getSource() == squares[4]) {
            squares[4].setEnabled(false);
            squares[4].setText(buttext);
          }
          else if (z.getSource() == squares[5]) {
            squares[5].setEnabled(false);
            squares[5].setText(buttext);
          }
          else if (z.getSource() == squares[6]) {
            squares[6].setEnabled(false);
            squares[6].setText(buttext);
          }
          else if (z.getSource() == squares[7]) {
            squares[7].setEnabled(false);
            squares[7].setText(buttext);
          }
          else if (z.getSource() == squares[8]) {
            squares[8].setEnabled(false);
            squares[8].setText(buttext);
          }
          wincheck();
          
        }
        
      });
    }
  }
  public void holder() {
    //panel to hold everything and lay it out
    holder = new JPanel();
    holder.setLayout(new BorderLayout());
    holder.add(play, BorderLayout.CENTER);
  }
  public void wincheck() {
    //checks for any winners
    //check row 1
    if (squares[0].getText() == squares[1].getText() && squares[2].getText() == squares[1].getText() && squares[0].getText() != "") {
      if (squares[0].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " + players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
    }
    //check row 2
    else if (squares[3].getText() == squares[4].getText() && squares[5].getText() == squares[3].getText() && squares[3].getText() != "") {
      if (squares[3].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " + players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
    }
    //check row 3
    else if (squares[6].getText() == squares[7].getText() && squares[8].getText() == squares[6].getText() && squares[6].getText() != "") {
      if (squares[6].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " + players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
    }
    //check diagonal left to right
    else if (squares[0].getText() == squares[4].getText() && squares[8].getText() == squares[0].getText() && squares[0].getText() != "") {
      if (squares[0].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " +  players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
    }
    //check diagonal right to left
    else if (squares[2].getText() == squares[4].getText() && squares[6].getText() == squares[4].getText() && squares[2].getText() != "") {
      if (squares[2].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " + players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
    }
    //check column 1
    else if (squares[0].getText() == squares[3].getText() && squares[6].getText() == squares[0].getText() && squares[0].getText() != "") {
      if (squares[0].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " + players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
    }
    //check column 2
    else if (squares[1].getText() == squares[4].getText() && squares[7].getText() == squares[1].getText() && squares[1].getText() != "") {
      if (squares[1].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " + players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
    }
    //check column 3
    else if (squares[2].getText() == squares[5].getText() && squares[8].getText() == squares[2].getText() && squares[2].getText() != "") {
      if (squares[2].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " + players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
    }
    else if (squares[0].getText() != "" && squares[1].getText() != "" && squares[2].getText() != ""  && squares[3].getText() != "" 
               && squares[4].getText() != "" && squares[5].getText() != "" && squares[6].getText() != "" && squares[7].getText() != "" 
               && squares[8].getText() != "" ){
      JOptionPane.showMessageDialog(null, "Cats game, it's a draw.", "TIE GAME", JOptionPane.INFORMATION_MESSAGE);
      d++;
      restartCheck();
      
    }
  }
  //checks if you want to restart after a game
  public void restartCheck() {
    int re = JOptionPane.showConfirmDialog(null, "Do you want to restart?", "Restart?", JOptionPane.YES_NO_OPTION);
    if (re == JOptionPane.YES_OPTION) {
      //if yes, re-enables buttons and reset the text
      playerShuffle();
      player.setText(players[0] + " it is your turn");
      for(int x = 0; x < 9; x++) {
        squares[x].setEnabled(true);
        squares[x].setText("");
      }
    }
    //checks winner by points
    else {
      if (p1 < p2) {
        winner = players[1];
      }
      else {
        winner = players[0];
      }
      //shows scoreboard and then winner.
      JOptionPane.showMessageDialog(null, players[0] + " " + p1 + " points.\n" + players[1] + " " + p2 + " points. " + d + " draws", "Score", JOptionPane.INFORMATION_MESSAGE);
      JOptionPane.showMessageDialog(null, winner + " wins with most points!", "Score", JOptionPane.INFORMATION_MESSAGE);
      System.exit(0);
    }
  }
  //shuffles players to choose who plays against who
  public void playerShuffle() {
    Collections.shuffle(s);
    Collections.shuffle(Arrays.asList(players));
  }
  //make an array with the original names in order
  public void copyPList() {
    for (int x = 0; x < players.length; x++) {
      OriP[x] = players[x];
    }
  }
  //find out who won
  public void getPlayer() {
    int y = 0;
    for (int x = 0; x < OriP.length;x++) {
      y++;
      if (winguy.equalsIgnoreCase(OriP[y])) {
        pscore[y]++;
        break;
      }
    }
  }
  //gets the score and transfers it to the score window
  public int[] getScore() {
    return pscore;
  }
  public String[] getNames() {
    return players;
  }
}


And finally my score file : my error generator.

import javax.swing.*;
import java.awt.*;
class score extends JFrame {
  window wind;
  private int pscores[];
  private JLabel player[];
  private String names[];
  private GridLayout grid;
  private JPanel score;
  private int y;
  public score(window win) {
    super("Player Scores");
    wind = win;
    setScore();
    names = new String[pscores.length];
    setNames();
    y = pscores.length;
    JLabel player[] = new JLabel[pscores.length];
    setGridSize();
    addToGrid();
    add(score);
  }
  public void setScore() {
    pscores = wind.getScore();
  }
  public void setNames() {
    names = wind.getNames();
  }
  public void setGridSize() {
    grid = new GridLayout(1,y);
  }
  public void addToGrid() {
    score = new JPanel();
    score.setLayout(grid);
    for (int x = 0; x < pscores.length; x++) {
      player[x] = new JLabel(names[x]);
      player[x].setFont(new Font(Font.SERIF, 0, 25));
      score.add(player[x]);
    }
  }
}


Right now i keep getting errors in the for loop at the very end of the score file with the JLabel array. If any insight can be given, it'd be epic.

Just for extra information, try to simplify it, as i am only in Grd.11 and have minimal knowledge on terms.

sorry for double post, but the edit button seems to not be visible for me or it doesn't exist.

I get a Null point error when the score window goes through the loop, i have search on null points and i know they can be caused three ways, but i do not understand how to fix them.
java.lang.NullPointerException
	at score.addToGrid(score.java:36)
	at score.<init>(score.java:20)
	at game.main(game.java:17)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)


This is the error and if you keep playing despite the error until someone wins, i get this :

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 4
	at window.getPlayer(window.java:274)
	at window.wincheck(window.java:201)
	at window$1.actionPerformed(window.java:104)
	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)



I hope that helps.

Is This A Good Question/Topic? 0
  • +

Replies To: Tic-Tac-Toe[GUI]: score window errors

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4189
  • View blog
  • Posts: 11,864
  • Joined: 18-April 07

Re: Tic-Tac-Toe[GUI]: score window errors

Posted 12 June 2013 - 04:11 PM

Well one issue is around this piece of code you have in window.java...

int y = 0;
for (int x = 0; x < OriP.length;x++) {
      y++;
      if (winguy.equalsIgnoreCase(OriP[y])) {
        pscore[y]++;
        break;
      }
}



Notice here that you are indexing OriP according to the value of "y" and not "x" which you are using in the loop. Instead of starting from the value of "x" (which would be zero) you are starting from 1 because you increment y before you use it. This is going to generate your off by one error because "y" will always be one more than "x" in this case. So when "x" is at your last player, "y" is going to be one more which is your array out of bounds error.

:)

This post has been edited by Martyr2: 12 June 2013 - 04:14 PM

Was This Post Helpful? 2
  • +
  • -

#3 zulfikar2  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 12-June 13

Re: Tic-Tac-Toe[GUI]: score window errors

Posted 12 June 2013 - 04:20 PM

View PostMartyr2, on 12 June 2013 - 04:11 PM, said:

Well one issue is around this piece of code you have in window.java...

int y = 0;
for (int x = 0; x < OriP.length;x++) {
      y++;
      if (winguy.equalsIgnoreCase(OriP[y])) {
        pscore[y]++;
        break;
      }
}



Notice here that you are indexing OriP according to the value of "y" and not "x" which you are using in the loop. Instead of starting from the value of "x" (which would be zero) you are starting from 1 because you increment y before you use it. This is going to generate your off by one error because "y" will always be one more than "x" in this case. So when "x" is at your last player, "y" is going to be one more which is your array out of bounds error.

:)/>


I can't believe i didn't notice that. Such a simple mistake does stump me, though i am still getting the first error, now it finally asks me for restartCheck();. I thank thee.

This is what i changed it to for future reference :
  public void getPlayer() {
    for (int x = 0; x < OriP.length;x++) {
      if (winguy.equalsIgnoreCase(OriP[x])) {
        pscore[x]++;
        break;
      }
    }
  }

Was This Post Helpful? 0
  • +
  • -

#4 schutzzz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 133
  • View blog
  • Posts: 338
  • Joined: 22-April 13

Re: Tic-Tac-Toe[GUI]: score window errors

Posted 12 June 2013 - 04:41 PM

private JLabel[] label = new JLabel[int];


There is a integer for how many labels are in that array. Then you can create a for loop

for(int i = 0; i < label.length; i++) {
    label[i] = new JLabel();
    label[i].setText(names[i]);
}



you can do this in the constructor. The reason it's a NullPointerException is because your label is null.

edit: messed up the new instance of JLabel, read the fixed

edit2: also it's bad convention to name your classes starting with a lowercase letter. i.e. make it Score, not score. same for your other classes.

This post has been edited by schutzzz: 12 June 2013 - 04:46 PM

Was This Post Helpful? 3
  • +
  • -

#5 zulfikar2  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 12-June 13

Re: Tic-Tac-Toe[GUI]: score window errors

Posted 12 June 2013 - 05:21 PM

WOW, i thank you so MUCH, you just made more sense to me than the countless tutorials i read to fix null points.

Now i have another question. Everything works and the labels are shown how i want them. How would i have that score window refresh everytime someone wins to update the score?
Was This Post Helpful? 0
  • +
  • -

#6 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 404
  • View blog
  • Posts: 1,006
  • Joined: 14-November 12

Re: Tic-Tac-Toe[GUI]: score window errors

Posted 12 June 2013 - 09:18 PM

You should create an update() method that will do specifically that, place it strategically within your code so that it will be called every time someone wins. If you're doing it graphically, you will need to clear the graphics context by drawing a big fat fillRect over it and then redraw the new score.
Was This Post Helpful? 0
  • +
  • -

#7 zulfikar2  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 12-June 13

Re: Tic-Tac-Toe[GUI]: score window errors

Posted 13 June 2013 - 12:12 PM

View PostFlukeshot, on 12 June 2013 - 09:18 PM, said:

You should create an update() method that will do specifically that, place it strategically within your code so that it will be called every time someone wins. If you're doing it graphically, you will need to clear the graphics context by drawing a big fat fillRect over it and then redraw the new score.


i am not using the rectangle create and stuff, but i am using just JLabels. I have tried update methods which would update it and i know where to place it and such, but they don't seem to work. I have tried revalidate(); and repaint(); but it seems like i am just doing it wrong. Any insight based on code above?
Was This Post Helpful? 0
  • +
  • -

#8 schutzzz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 133
  • View blog
  • Posts: 338
  • Joined: 22-April 13

Re: Tic-Tac-Toe[GUI]: score window errors

Posted 13 June 2013 - 12:26 PM

if you have it keep count of wins just have the JLabel set the text.to the wins once the user wins.

label.setText("Wins: " + winCount);


Was This Post Helpful? 0
  • +
  • -

#9 zulfikar2  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 12-June 13

Re: Tic-Tac-Toe[GUI]: score window errors

Posted 13 June 2013 - 12:55 PM

  public void refresher() {
    sc.refreshS();
  }


Added this little snippet to window.java and then called it everytime someone won.

And in score for the method added this :

  public void refreshS() {
    setScore();
    for (int x = 0; x < pscores.length; x++) {
      player[x].setText(names[x] + "                 " + pscores[x]);
    }
  }


gives me :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at window.refresher(window.java:309)
	at window.wincheck(window.java:143)
	at Window$1.actionPerformed(window.java:108)
	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
	at java.awt.Component.processMouseEvent(Unknown Source)
	at javax.swing.JComponent.processMouseEvent(Unknown Source)
	at java.awt.Component.processEvent(Unknown Source)
	at java.awt.Container.processEvent(Unknown Source)
	at java.awt.Component.dispatchEventImpl(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.window.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
	at java.awt.EventQueue.access$200(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue$4.run(Unknown Source)
	at java.awt.EventQueue$4.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue.dispatchEvent(Unknown Source)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.run(Unknown Source)
> 


I am stumped.
Was This Post Helpful? 0
  • +
  • -

#10 schutzzz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 133
  • View blog
  • Posts: 338
  • Joined: 22-April 13

Re: Tic-Tac-Toe[GUI]: score window errors

Posted 13 June 2013 - 02:37 PM

Can you post your updated class so I can try and fix the error?

I'm assuming the NullPointerException is in here. Make sure that every variable that is used here isn't set to null before this method gets called.
public void refreshS() {
  setScore();
  for (int x = 0; x < pscores.length; x++) {
    player[x].setText(names[x] + "                 " + pscores[x]);
  }
}



This post has been edited by schutzzz: 13 June 2013 - 02:43 PM

Was This Post Helpful? 0
  • +
  • -

#11 zulfikar2  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 12-June 13

Re: Tic-Tac-Toe[GUI]: score window errors

Posted 13 June 2013 - 02:46 PM

Sure, here's it updated

Game.java :

import javax.swing.*;
import java.awt.*;
public class Game {
  static int height = 0; // height of game windows
  static int width = 0; // width of game window
  public static void main(String[] args){
    //create new instance of main game window
    Window win = new Window();
    //parameters/settings for the new window
    win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    height = 500;
    width = 500;
    win.setSize(width, height);
    win.setLocationRelativeTo(null);
    win.setVisible(true);
    win.setResizable(false);
    win.setForeground(Color.RED);
    win.setBackground(Color.BLACK);
    //create new instance of score window
    Score sc = new Score(win);
    //parameters/settings for the new score window
    sc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    sc.setSize(width-100, height-100);
    sc.setVisible(true);
    sc.setResizable(false);
    sc.setForeground(Color.RED);
    sc.setBackground(Color.BLACK);
  }
}


window.java

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class Window extends JFrame {
  private final GridLayout grid = new GridLayout(3,3);
  private JLabel player;
  private String players[] = new String[1]; //array with player names
  private String OriP[] = new String[1]; //array with player names original
  private int pcheck = 1; //Mod 2 to get even guy turn
  private JButton squares[] = new JButton[9];
  private JPanel play, holder;
  private String buttext = "O";
  private int d = 0;//draw count 
  private int p1 = 0;//player 1 points
  private int p2 = 0;//player 2 points
  private int pscore[] = new int[1]; //array with player's score
  private String winner = "";//The winner at end
  private String pcount = "";
  private String winguy = "";
  java.util.List s = new ArrayList();
  Score sc;
Score score;
  public Window(){ 
    //Title
    super("Tic-Tac-Toe     By : Zulfikar Yusufali");
    pcount = JOptionPane.showInputDialog(null, "How many players are playing?", "Players", JOptionPane.QUESTION_MESSAGE); 
    players(Integer.parseInt(pcount));
    playboard();
    holder();
    add(play);
    copyPList();
    playerShuffle();
    player = new JLabel(players[0] + " it is your turn.");
    player.setForeground(Color.RED);
    add(player, BorderLayout.SOUTH);
  }
  public void players(int p) {
    players = new String[p];
    pscore = new int[p];
    OriP = new String[p];
    for (int x = 0; x < p; x++) {
      players[x] = JOptionPane.showInputDialog(null,"What is your name?","Player " + (x+1), JOptionPane.QUESTION_MESSAGE);
    }
  }
  public void playboard() {
    play = new JPanel();
    play.setLayout(grid);
    //adds the buttons and all the properties for it
    for (int y = 0; y<9; y++) {
      squares[y] = new JButton("");
      squares[y].setFont(new Font(Font.SERIF, 0, 50));
      squares[y].setForeground(Color.RED);
      squares[y].setBackground(Color.BLACK);
      play.add(squares[y]);
      squares[y].addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent z) {
          pcheck++;
          //checks whos turn it is
          if (pcheck%2 == 0) {
            player.setText(players[1] + " it is your turn");
            buttext = "X";
          }
          else {
            player.setText(players[0] + " it is your turn");
            buttext = "O";
          }
          //actionListener for all button press events
          if (z.getSource() == squares[0]) {
            squares[0].setEnabled(false);
            squares[0].setText(buttext);
          }
          else if (z.getSource() == squares[1]) {
            squares[1].setEnabled(false);
            squares[1].setText(buttext);
          }
          else if (z.getSource() == squares[2]) {
            squares[2].setEnabled(false);
            squares[2].setText(buttext);
          }
          else if (z.getSource() == squares[3]) {
            squares[3].setEnabled(false);
            squares[3].setText(buttext);
          }
          else if (z.getSource() == squares[4]) {
            squares[4].setEnabled(false);
            squares[4].setText(buttext);
          }
          else if (z.getSource() == squares[5]) {
            squares[5].setEnabled(false);
            squares[5].setText(buttext);
          }
          else if (z.getSource() == squares[6]) {
            squares[6].setEnabled(false);
            squares[6].setText(buttext);
          }
          else if (z.getSource() == squares[7]) {
            squares[7].setEnabled(false);
            squares[7].setText(buttext);
          }
          else if (z.getSource() == squares[8]) {
            squares[8].setEnabled(false);
            squares[8].setText(buttext);
          }
          wincheck();
          
        }
        
      });
    }
  }
  public void holder() {
    //panel to hold everything and lay it out
    holder = new JPanel();
    holder.setLayout(new BorderLayout());
    holder.add(play, BorderLayout.CENTER);
  }
  public void wincheck() {
    //checks for any winners
    //check row 1
    if (squares[0].getText() == squares[1].getText() && squares[2].getText() == squares[1].getText() && squares[0].getText() != "") {
      if (squares[0].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " + players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
    }
    //check row 2
    else if (squares[3].getText() == squares[4].getText() && squares[5].getText() == squares[3].getText() && squares[3].getText() != "") {
      if (squares[3].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " + players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
    }
    //check row 3
    else if (squares[6].getText() == squares[7].getText() && squares[8].getText() == squares[6].getText() && squares[6].getText() != "") {
      if (squares[6].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " + players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
    }
    //check diagonal left to right
    else if (squares[0].getText() == squares[4].getText() && squares[8].getText() == squares[0].getText() && squares[0].getText() != "") {
      if (squares[0].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " +  players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
    }
    //check diagonal right to left
    else if (squares[2].getText() == squares[4].getText() && squares[6].getText() == squares[4].getText() && squares[2].getText() != "") {
      if (squares[2].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " + players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        restartCheck();
      }
    }
    //check column 1
    else if (squares[0].getText() == squares[3].getText() && squares[6].getText() == squares[0].getText() && squares[0].getText() != "") {
      if (squares[0].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " + players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
    }
    //check column 2
    else if (squares[1].getText() == squares[4].getText() && squares[7].getText() == squares[1].getText() && squares[1].getText() != "") {
      if (squares[1].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " + players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
    }
    //check column 3
    else if (squares[2].getText() == squares[5].getText() && squares[8].getText() == squares[2].getText() && squares[2].getText() != "") {
      if (squares[2].getText() == "X") {
        JOptionPane.showMessageDialog(null, "You win " + players[0], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
      else {
        JOptionPane.showMessageDialog(null, "You win " + players[1], "Congratulations", JOptionPane.INFORMATION_MESSAGE);
        getPlayer();
        refresher();
        restartCheck();
      }
    }
    //check for draw
    else if (squares[0].getText() != "" && squares[1].getText() != "" && squares[2].getText() != ""  && squares[3].getText() != "" 
               && squares[4].getText() != "" && squares[5].getText() != "" && squares[6].getText() != "" && squares[7].getText() != "" 
               && squares[8].getText() != "" ){
      JOptionPane.showMessageDialog(null, "Cats game, it's a draw.", "TIE GAME", JOptionPane.INFORMATION_MESSAGE);
      d++;
      refresher();
      restartCheck();
      
    }
  }
  //checks if you want to restart after a game
  public void restartCheck() {
    int re = JOptionPane.showConfirmDialog(null, "Do you want to restart?", "Restart?", JOptionPane.YES_NO_OPTION);
    if (re == JOptionPane.YES_OPTION) {
      //if yes, re-enables buttons and reset the text
      playerShuffle();
      player.setText(players[0] + " it is your turn");
      for(int x = 0; x < 9; x++) {
        squares[x].setEnabled(true);
        squares[x].setText("");
      }
    }
    //checks winner by points
    else {
      if (p1 < p2) {
        winner = players[1];
      }
      else {
        winner = players[0];
      }
      //shows scoreboard and then winner.
      JOptionPane.showMessageDialog(null, players[0] + " " + p1 + " points.\n" + players[1] + " " + p2 + " points. " + d + " draws", "Score", JOptionPane.INFORMATION_MESSAGE);
      JOptionPane.showMessageDialog(null, winner + " wins with most points!", "Score", JOptionPane.INFORMATION_MESSAGE);
      System.exit(0);
    }
  }
  //shuffles players to choose who plays against who
  public void playerShuffle() {
    Collections.shuffle(s);
    Collections.shuffle(Arrays.asList(players));
  }
  //make an array with the original names in order
  public void copyPList() {
    for (int x = 0; x < players.length; x++) {
      OriP[x] = players[x];
    }
  }
  //find out who won
  public void getPlayer() {
    for (int x = 0; x < OriP.length;x++) {
      if (winguy.equalsIgnoreCase(OriP[x])) {
        pscore[x]++;
        break;
      }
    }
  }
  //gets the score and transfers it to the score window
  public int[] getScore() {
    return pscore;
  }
  //gets the names and transfer it to the score window
  public String[] getNames() {
    return players;
  }
  //refreshes score window
  public void refresher() {
    sc.refreshS();
  }
}


Score.java

import javax.swing.*;
import java.awt.*;
class Score extends JFrame {
  Window wind;
  private int pscores[];
  private String names[];
  private GridLayout grid;
  private JPanel score;
  private int z = 1, y;
  private JLabel player[] = new JLabel[1];
  public Score(Window win) {
    //Title
    super("Player Scores");
    wind = win;
    setScore();
    names = new String[pscores.length];
    setNames();
    y = pscores.length;
    z = y;
    player = new JLabel[z];
    setGridSize();
    addToGrid();
    add(score);
  }
  //gets score from other class
  public void setScore() {
    pscores = wind.getScore();
  }
  //gets names from other class
  public void setNames() {
    names = wind.getNames();
  }
  //sets grid for placement of labels
  public void setGridSize() {
    grid = new GridLayout(y,1);
  }
  //adds components to the main panel with grid layout
  public void addToGrid() {
    score = new JPanel();
    score.setLayout(grid);
    //adds labels and its properties
    for (int x = 0; x < pscores.length; x++) {
      player[x] = new JLabel();
      player[x].setText(names[x] + "                 " + pscores[x]);
      player[x].setFont(new Font(Font.SERIF, 0, 25));
      score.add(player[x]);
    }
  }
  //refreshes score window
  public void refreshS() {
    setScore();
    for (int x = 0; x < pscores.length; x++) {
      player[x] = new JLabel();
      player[x].setText(names[x] + "                 " + pscores[x]);
    }
  }
}

Was This Post Helpful? 0
  • +
  • -

#12 zulfikar2  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 12-June 13

Re: Tic-Tac-Toe[GUI]: score window errors

Posted 16 June 2013 - 04:01 PM

Any help please?
Was This Post Helpful? 0
  • +
  • -

#13 schutzzz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 133
  • View blog
  • Posts: 338
  • Joined: 22-April 13

Re: Tic-Tac-Toe[GUI]: score window errors

Posted 16 June 2013 - 04:41 PM

Your code is difficult for me to read just because there is no spacing. It could be something simple you are missing, but I believe it's your line 54 in Score that's producing the NullPointerException? Go through your program to what's calling your refreshS method. Keep back tracing the methods you are calling to make sure those variables are initialized and aren't set to null at any point. If you fix the spacing in your classes i'll gladly take another look for you when it's easier for me to read.
Was This Post Helpful? 0
  • +
  • -

#14 zulfikar2  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 12-June 13

Re: Tic-Tac-Toe[GUI]: score window errors

Posted 16 June 2013 - 05:04 PM

View Postschutzzz, on 16 June 2013 - 04:41 PM, said:

Your code is difficult for me to read just because there is no spacing. It could be something simple you are missing, but I believe it's your line 54 in Score that's producing the NullPointerException? Go through your program to what's calling your refreshS method. Keep back tracing the methods you are calling to make sure those variables are initialized and aren't set to null at any point. If you fix the spacing in your classes i'll gladly take another look for you when it's easier for me to read.


alright, let's see if i can fix it without posting to your bank of knowledge and do with the little you gave me. I'll post if i need nay more aide.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1