0

I wrote a fairly simple program using a GUI template to learn about adding some form of GUI in java. I completed the program only to discover that it cant be run outside of the IDE without a main method. The program works fine inside Eclipse IDE, but useless otherwise. How do I go about adding a main class so it can be executed as a .jar?

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

public class Game extends JApplet implements ActionListener {
    // Create all labels, textfields and buttons needed (in order)




    /**
     *  This is a tic tac toe game made with the purposes of learning java
     */
    private static final long serialVersionUID = 1L;
    JButton firstButton;
    JButton secondButton;
    JButton thirdButton;
    JButton fourthButton;
    JButton fithButton;
    JButton sixthButton;
    JButton seventhButton;
    JButton eighthButton;
    JButton ninthButton;

    //this is the position value checker which are later set to x and o
    String[] posCheck = { "", "", "", "", "", "", "", "", "" };

    // score count JLABELs to display the score inside the game pane.
    JLabel scoreP1;
    JLabel scoreP2;

    // this is used for formatting purposes or something like that, I guess.
    JLabel blank;

    // score count variables for both players, they both start at 0.
    int scoreCount1 = 0, scoreCount2 = 0;
    int gamesPlayed = -1;
    boolean gameDone = false;
    int k;
    String prevWinner = "";

    // Create any global variables/arrays needed later in the program (final)
    Container pane = getContentPane();

    //this sets the tile to X or O depending on who's turn it is
    String[] symbol = { "O", "X" };
    int turnCounter = 0;
    int tieChecker = 0;

    // Sets up GUI components.
    public void init() {

        pane.setLayout(new GridLayout(4, 3));

        setSize(500, 500);

        // Adds jlabel for scores
        scoreP1 = new JLabel();
        scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));

        scoreP2 = new JLabel();
        scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));

        blank = new JLabel();
        blank.setText(prevWinner);

        // these are the JButtons that go in the game panel along with action
        // listeners
        firstButton = new JButton();
        firstButton.addActionListener(this);

        secondButton = new JButton();
        secondButton.addActionListener(this);

        thirdButton = new JButton();
        thirdButton.addActionListener(this);

        fourthButton = new JButton();
        fourthButton.addActionListener(this);

        fithButton = new JButton();
        fithButton.addActionListener(this);

        sixthButton = new JButton();
        sixthButton.addActionListener(this);

        seventhButton = new JButton();
        seventhButton.addActionListener(this);

        eighthButton = new JButton();
        eighthButton.addActionListener(this);

        ninthButton = new JButton();
        ninthButton.addActionListener(this);

        pane.add(firstButton, 0); // second parameter is the index on pane
        pane.add(secondButton, 1);
        pane.add(thirdButton, 2);
        pane.add(fourthButton, 3);
        pane.add(fithButton, 4);
        pane.add(sixthButton, 5);
        pane.add(seventhButton, 6);
        pane.add(eighthButton, 7);
        pane.add(ninthButton, 8);

        pane.add(scoreP1);
        pane.add(blank);
        pane.add(scoreP2);

        gamesPlayed++;

        setContentPane(pane);
    } // init method

    // checks for mouse clicks here.
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof JButton) {
            if (e.getSource() == firstButton)
                revealButton(firstButton, 0);
            else if (e.getSource() == secondButton)
                revealButton(secondButton, 1);
            else if (e.getSource() == thirdButton)
                revealButton(thirdButton, 2);
            else if (e.getSource() == fourthButton)
                revealButton(fourthButton, 3);
            else if (e.getSource() == fithButton)
                revealButton(fithButton, 4);
            else if (e.getSource() == sixthButton)
                revealButton(sixthButton, 5);
            else if (e.getSource() == seventhButton)
                revealButton(seventhButton, 6);
            else if (e.getSource() == eighthButton)
                revealButton(eighthButton, 7);
            else if (e.getSource() == ninthButton)
                revealButton(ninthButton, 8);

        }
    } // actionPerformed method

    // respond to button pushed
    public void revealButton(JButton button, int index) {

        // removes the indicated button from pane
        pane.remove(button);

        // creates a new text field to take the place of the button, makes it
        // uneditable and sets background colour
        JTextField textField = new JTextField();
        textField.setEditable(false);
        textField.setBackground(Color.WHITE);

        // sets the alignment for the text in the field
        textField.setHorizontalAlignment(SwingConstants.CENTER);

        // adds the new textfield to the pane at the location of the old button
        pane.add(textField, index);
        posCheck[index] = symbol[(turnCounter % 2)];
        prevWinner = "Player (" + symbol[(turnCounter % 2)]
                + ") is the winner!";

        // re-creates pane with new information
        setContentPane(pane);

        // this sets the text field to either X or O depending who placed last.
        textField.setText(symbol[(turnCounter) % 2]);
        button.setEnabled(false);

        // this is a counter to check if it is a cats game.
        tieChecker++;

        // check for winner X here
        if (((posCheck[0] == "X") && (posCheck[1] == "X") && (posCheck[2] == "X"))
                || ((posCheck[3] == "X") && (posCheck[4] == "X") && (posCheck[5] == "X"))
                || ((posCheck[6] == "X") && (posCheck[7] == "X") && (posCheck[8] == "X"))
                || ((posCheck[0] == "X") && (posCheck[3] == "X") && (posCheck[6] == "X"))
                || ((posCheck[1] == "X") && (posCheck[4] == "X") && (posCheck[7] == "X"))
                || ((posCheck[2] == "X") && (posCheck[5] == "X") && (posCheck[8] == "X"))
                || ((posCheck[0] == "X") && (posCheck[4] == "X") && (posCheck[8] == "X"))
                || ((posCheck[2] == "X") && (posCheck[4] == "X") && (posCheck[6] == "X"))) {

            // this part updates the winner score then refreshes the text field
            // to reflect the change
            scoreCount1++;
            scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));
            blank.setText("Player (X) Is the winner.");

            gameDone = true;
            turnCounter++;
        }
        // this checks if O has won the game.
        else if (((posCheck[0] == "O") && (posCheck[1] == "O") && (posCheck[2] == "O"))
                || ((posCheck[3] == "O") && (posCheck[4] == "O") && (posCheck[5] == "O"))
                || ((posCheck[6] == "O") && (posCheck[7] == "O") && (posCheck[8] == "O"))
                || ((posCheck[0] == "O") && (posCheck[3] == "O") && (posCheck[6] == "O"))
                || ((posCheck[1] == "O") && (posCheck[4] == "O") && (posCheck[7] == "O"))
                || ((posCheck[2] == "O") && (posCheck[5] == "O") && (posCheck[8] == "O"))
                || ((posCheck[0] == "O") && (posCheck[4] == "O") && (posCheck[8] == "O"))
                || ((posCheck[2] == "O") && (posCheck[4] == "O") && (posCheck[6] == "O"))) {
            // this part updates the winner score then refreshes the text field
            // to reflect the change
            scoreCount2++;
            scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));
            blank.setText("Player (O) Is the winner.");

            gameDone = true;
            turnCounter++;
        }

        // this checks if there has been a tie in the game
        else if (tieChecker >= 9) {
            prevWinner = ("It's a cat's game!");
            tieChecker = 0;
            gameDone = true;
            turnCounter++;
        }

        // this makes sure the game doesnt end prematurely
        else {
            gameDone = false;
        }

        // this if statement is engaged when the game is done and resets the
        // board
        if (gameDone == true) {
            pane.removeAll();
            textField.removeAll();
            tieChecker = 0;
            init();

            posCheck[0] = "";
            posCheck[1] = "";
            posCheck[2] = "";
            posCheck[3] = "";
            posCheck[4] = "";
            posCheck[5] = "";
            posCheck[6] = "";
            posCheck[7] = "";
            posCheck[8] = "";
            posCheck[9] = "";

        }// end of reset sequence

        turnCounter++;

        blank.setText("Games Played: " + gamesPlayed);
    }


}
Matt Smith
  • 174
  • 2
  • 14
  • Im confused how you can run this in an IDE but not when you build the JAR... all Java programs need a main method to run, IDE or otherwise. Why not just package up the main method in the source file that the IDE is using and use that? – Ryan J Jun 05 '14 at 06:17
  • http://stackoverflow.com/questions/932052/why-do-applets-not-need-a-main – Ninad Pingale Jun 05 '14 at 06:20
  • 1
    since it's an applet, don't. run it in your browser – Stultuske Jun 05 '14 at 06:27
  • FYI, you have an error in your code: `posCheck[9] = "";` that line causes an `ArrayIndexOutOfBoundsException`, as that array only has 9 elements. – Ryan J Jun 05 '14 at 06:38
  • @RyanJ strange, it doesnt seem to function properly (but still runs) when i comment out that line, but works fine when i keep it there. – Matt Smith Jun 05 '14 at 06:41
  • Odd. It fixes it for me if so. Well, it's off topic anyways, just thought I would point it out. Good luck. – Ryan J Jun 05 '14 at 06:44

2 Answers2

0

You can convert JApplet to JFrame - Change your public init() method to public static void main (String args[]).Then create an instance of JFrame JFrame frame = new JFrame(); Then add components to it.

or

Add existing applet to JFrame - Adding JApplet into JFrame

So using second method your code would be -

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

public class Game extends JApplet implements ActionListener {
    // Create all labels, textfields and buttons needed (in order)




    /**
     *  This is a tic tac toe game made with the purposes of learning java
     */
    private static final long serialVersionUID = 1L;
    JButton firstButton;
    JButton secondButton;
    JButton thirdButton;
    JButton fourthButton;
    JButton fithButton;
    JButton sixthButton;
    JButton seventhButton;
    JButton eighthButton;
    JButton ninthButton;

    //this is the position value checker which are later set to x and o
    String[] posCheck = { "", "", "", "", "", "", "", "", "" };

    // score count JLABELs to display the score inside the game pane.
    JLabel scoreP1;
    JLabel scoreP2;

    // this is used for formatting purposes or something like that, I guess.
    JLabel blank;

    // score count variables for both players, they both start at 0.
    int scoreCount1 = 0, scoreCount2 = 0;
    int gamesPlayed = -1;
    boolean gameDone = false;
    int k;
    String prevWinner = "";

    // Create any global variables/arrays needed later in the program (final)
    Container pane = getContentPane();

    //this sets the tile to X or O depending on who's turn it is
    String[] symbol = { "O", "X" };
    int turnCounter = 0;
    int tieChecker = 0;

    // Sets up GUI components.
    public void init() {

        pane.setLayout(new GridLayout(4, 3));

        setSize(500, 500);

        // Adds jlabel for scores
        scoreP1 = new JLabel();
        scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));

        scoreP2 = new JLabel();
        scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));

        blank = new JLabel();
        blank.setText(prevWinner);

        // these are the JButtons that go in the game panel along with action
        // listeners
        firstButton = new JButton();
        firstButton.addActionListener(this);

        secondButton = new JButton();
        secondButton.addActionListener(this);

        thirdButton = new JButton();
        thirdButton.addActionListener(this);

        fourthButton = new JButton();
        fourthButton.addActionListener(this);

        fithButton = new JButton();
        fithButton.addActionListener(this);

        sixthButton = new JButton();
        sixthButton.addActionListener(this);

        seventhButton = new JButton();
        seventhButton.addActionListener(this);

        eighthButton = new JButton();
        eighthButton.addActionListener(this);

        ninthButton = new JButton();
        ninthButton.addActionListener(this);

        pane.add(firstButton, 0); // second parameter is the index on pane
        pane.add(secondButton, 1);
        pane.add(thirdButton, 2);
        pane.add(fourthButton, 3);
        pane.add(fithButton, 4);
        pane.add(sixthButton, 5);
        pane.add(seventhButton, 6);
        pane.add(eighthButton, 7);
        pane.add(ninthButton, 8);

        pane.add(scoreP1);
        pane.add(blank);
        pane.add(scoreP2);

        gamesPlayed++;

        setContentPane(pane);
    } // init method

    // checks for mouse clicks here.
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof JButton) {
            if (e.getSource() == firstButton)
                revealButton(firstButton, 0);
            else if (e.getSource() == secondButton)
                revealButton(secondButton, 1);
            else if (e.getSource() == thirdButton)
                revealButton(thirdButton, 2);
            else if (e.getSource() == fourthButton)
                revealButton(fourthButton, 3);
            else if (e.getSource() == fithButton)
                revealButton(fithButton, 4);
            else if (e.getSource() == sixthButton)
                revealButton(sixthButton, 5);
            else if (e.getSource() == seventhButton)
                revealButton(seventhButton, 6);
            else if (e.getSource() == eighthButton)
                revealButton(eighthButton, 7);
            else if (e.getSource() == ninthButton)
                revealButton(ninthButton, 8);

        }
    } // actionPerformed method

    // respond to button pushed
    public void revealButton(JButton button, int index) {

        // removes the indicated button from pane
        pane.remove(button);

        // creates a new text field to take the place of the button, makes it
        // uneditable and sets background colour
        JTextField textField = new JTextField();
        textField.setEditable(false);
        textField.setBackground(Color.WHITE);

        // sets the alignment for the text in the field
        textField.setHorizontalAlignment(SwingConstants.CENTER);

        // adds the new textfield to the pane at the location of the old button
        pane.add(textField, index);
        posCheck[index] = symbol[(turnCounter % 2)];
        prevWinner = "Player (" + symbol[(turnCounter % 2)]
                + ") is the winner!";

        // re-creates pane with new information
        setContentPane(pane);

        // this sets the text field to either X or O depending who placed last.
        textField.setText(symbol[(turnCounter) % 2]);
        button.setEnabled(false);

        // this is a counter to check if it is a cats game.
        tieChecker++;

        // check for winner X here
        if (((posCheck[0] == "X") && (posCheck[1] == "X") && (posCheck[2] == "X"))
                || ((posCheck[3] == "X") && (posCheck[4] == "X") && (posCheck[5] == "X"))
                || ((posCheck[6] == "X") && (posCheck[7] == "X") && (posCheck[8] == "X"))
                || ((posCheck[0] == "X") && (posCheck[3] == "X") && (posCheck[6] == "X"))
                || ((posCheck[1] == "X") && (posCheck[4] == "X") && (posCheck[7] == "X"))
                || ((posCheck[2] == "X") && (posCheck[5] == "X") && (posCheck[8] == "X"))
                || ((posCheck[0] == "X") && (posCheck[4] == "X") && (posCheck[8] == "X"))
                || ((posCheck[2] == "X") && (posCheck[4] == "X") && (posCheck[6] == "X"))) {

            // this part updates the winner score then refreshes the text field
            // to reflect the change
            scoreCount1++;
            scoreP1.setText("Player (X) score: " + String.valueOf(scoreCount1));
            blank.setText("Player (X) Is the winner.");

            gameDone = true;
            turnCounter++;
        }
        // this checks if O has won the game.
        else if (((posCheck[0] == "O") && (posCheck[1] == "O") && (posCheck[2] == "O"))
                || ((posCheck[3] == "O") && (posCheck[4] == "O") && (posCheck[5] == "O"))
                || ((posCheck[6] == "O") && (posCheck[7] == "O") && (posCheck[8] == "O"))
                || ((posCheck[0] == "O") && (posCheck[3] == "O") && (posCheck[6] == "O"))
                || ((posCheck[1] == "O") && (posCheck[4] == "O") && (posCheck[7] == "O"))
                || ((posCheck[2] == "O") && (posCheck[5] == "O") && (posCheck[8] == "O"))
                || ((posCheck[0] == "O") && (posCheck[4] == "O") && (posCheck[8] == "O"))
                || ((posCheck[2] == "O") && (posCheck[4] == "O") && (posCheck[6] == "O"))) {
            // this part updates the winner score then refreshes the text field
            // to reflect the change
            scoreCount2++;
            scoreP2.setText("Player (O) score: " + String.valueOf(scoreCount2));
            blank.setText("Player (O) Is the winner.");

            gameDone = true;
            turnCounter++;
        }

        // this checks if there has been a tie in the game
        else if (tieChecker >= 9) {
            prevWinner = ("It's a cat's game!");
            tieChecker = 0;
            gameDone = true;
            turnCounter++;
        }

        // this makes sure the game doesnt end prematurely
        else {
            gameDone = false;
        }

        // this if statement is engaged when the game is done and resets the
        // board
        if (gameDone == true) {
            pane.removeAll();
            textField.removeAll();
            tieChecker = 0;
            init();

            posCheck[0] = "";
            posCheck[1] = "";
            posCheck[2] = "";
            posCheck[3] = "";
            posCheck[4] = "";
            posCheck[5] = "";
            posCheck[6] = "";
            posCheck[7] = "";
            posCheck[8] = "";
            posCheck[9] = "";

        }// end of reset sequence

        turnCounter++;

        blank.setText("Games Played: " + gamesPlayed);
    }

    public static void main(String[] args) {

        JFrame baseFrame = new JFrame();
        Game gameObject = new Game();
        gameObject.init();
        baseFrame.setVisible(true);
        baseFrame.getContentPane().add(gameObject);
    }
}
Community
  • 1
  • 1
Ninad Pingale
  • 6,801
  • 5
  • 32
  • 55
0

If you insist on keeping it as an Applet, make another class and do this:

import javax.swing.JFrame;


public class Main {
    public static void main(String[] args) {

        JFrame frame = new JFrame();
        Game g = new Game();
        g.init();
        frame.getContentPane().add(g);
        frame.pack();
        frame.setVisible(true);
    }
}
Ryan J
  • 8,275
  • 3
  • 25
  • 28
  • Thanks, this seems to work. The only issue i am having now is exporting it with the new class as the main class. `no main manifest attribute, in "C:\...\ticTacToe.jar"` – Matt Smith Jun 05 '14 at 06:51
  • UPDATE: a quick google search took me to the eclipse help page. problem solved – Matt Smith Jun 05 '14 at 07:00