Java 将main添加到预先存在的程序中

Java 将main添加到预先存在的程序中,java,methods,jbutton,japplet,Java,Methods,Jbutton,Japplet,我使用GUI模板编写了一个相当简单的程序,以了解如何在java中添加某种形式的GUI。我完成了这个程序,却发现如果没有main方法,它不能在IDE之外运行。该程序在EclipseIDE中运行良好,但在其他方面毫无用处。如何添加一个主类,使其可以作为.jar执行 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Game extends JApplet implements ActionL

我使用GUI模板编写了一个相当简单的程序,以了解如何在java中添加某种形式的GUI。我完成了这个程序,却发现如果没有main方法,它不能在IDE之外运行。该程序在EclipseIDE中运行良好,但在其他方面毫无用处。如何添加一个主类,使其可以作为.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);
    }


}

可以将JApplet转换为JFrame-将public init()方法更改为public static void main(字符串args[])。然后创建JFrame的实例 JFrame=新JFrame();然后向其中添加组件

将现有小程序添加到JFrame-

因此,使用第二种方法,您的代码将-

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);
    }
}

如果坚持将其作为小程序保存,请创建另一个类并执行以下操作:

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);
    }
}

我很困惑如何在IDE中运行它,而不是在构建JAR时。。。所有Java程序都需要一个main方法来运行,不管是IDE还是其他方法。为什么不将IDE正在使用的源文件中的main方法打包并使用它呢?因为它是一个小程序,所以不要这样做。在浏览器中运行它,您的代码中有一个错误:
posCheck[9]=“”
该行导致出现
ArrayIndexOutOfBoundsException
,因为该数组只有9个元素。@RyanJ奇怪,当我注释掉该行时,它似乎运行不正常(但仍在运行),但当我保留该行时,它工作正常。这两种解决方案似乎都给了我一个错误
无法在静态上下文中使用它
谢谢,这似乎奏效了。我现在遇到的唯一问题是将新类作为主类导出它<代码>没有主清单属性,在“C:\…\ticTacToe.jar”中更新:一个快速的谷歌搜索将我带到eclipse帮助页面。问题解决