【问题标题】:Adding a main to a pre existing program向预先存在的程序添加主程序
【发布时间】:2014-06-05 06:09:57
【问题描述】:

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


}

【问题讨论】:

  • 我很困惑如何在 IDE 中运行它,但在构建 JAR 时却没有……所有 Java 程序都需要一个 main 方法来运行,IDE 或其他方式。为什么不直接将 IDE 正在使用的源文件中的 main 方法打包并使用呢?
  • 因为它是一个小程序,所以不要。在浏览器中运行它
  • 仅供参考,您的代码中有一个错误:posCheck[9] = ""; 该行导致ArrayIndexOutOfBoundsException,因为该数组只有 9 个元素。
  • @RyanJ 奇怪,当我注释掉该行时,它似乎无法正常运行(但仍然运行),但当我将其保留在那里时,它工作正常。

标签: java methods jbutton japplet


【解决方案1】:

如果您坚持将其保留为 Applet,请创建另一个类并执行此操作:

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

【讨论】:

  • 谢谢,这似乎有效。我现在唯一遇到的问题是以新类作为主类导出它。 no main manifest attribute, in "C:\...\ticTacToe.jar"
  • 更新:快速谷歌搜索带我到 Eclipse 帮助页面。问题解决了
【解决方案2】:

您可以将 JApplet 转换为 JFrame - 将您的 public init() 方法更改为 public static void main (String args[])。然后创建 JFrame 的实例 JFrame 框架 = 新的 JFrame();然后给它添加组件。

将现有小程序添加到 JFrame - Adding JApplet into 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);
    }
}

【讨论】:

  • 两种解决方案似乎都给了我错误Cannot use this in a static context
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-13
  • 2012-07-05
  • 2015-11-22
  • 1970-01-01
  • 2021-05-22
相关资源
最近更新 更多