【问题标题】:gui and main() methodgui 和 main() 方法
【发布时间】:2016-07-27 03:20:36
【问题描述】:

我目前正在用 Java 创建一个mancala-game。这是我目前所拥有的:

package mancala;

import javax.swing.*;

public class Game  {

    private JLabel start;
    private JButton startBtn;
    private JPanel panel;
    private JFrame frame;

    public Game(){
        createForm();
        addButtons();

        frame.add(panel);
        frame.setVisible(true);
    }

    public void createForm() {
        frame = new JFrame();
        frame.setTitle("Mancala");
        frame.setSize(500,500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void addButtons() {
        startBtn = new JButton("Start");
    }
}

这会引发以下错误:

Error: Main method not found in class mancala.Game, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

但是当我添加 main-method 时,它仍然坏了,我必须采取什么步骤才能使它工作?

【问题讨论】:

  • 你只有这门课吗?
  • 你是什么意思它仍然坏了?你看到了什么错误?
  • 到目前为止是的,它是我的第一个 java gui,所以到处玩看看它是如何工作的。当我添加主要方法时,屏幕上没有显示任何内容。我需要从 main() 调用一个类吗?
  • 使用main(String[]) 方法显示变体..

标签: java swing user-interface main


【解决方案1】:

您当前的课程没有什么可以执行的。为了创建 Game 类的新实例,您需要一个额外的类。试着把 Game-Class 想象成一个蓝图,它必须被“使用”(被另一个类)。

在您的新类中,您必须调用 Game 类的构造函数才能使用它。新类的一个例子:

package mancala;

public class RunGame {

    public static void main(String[] args) {
        Game game = new Game();
        // Now you can do funky stuff with your generated Instance :)
    }
}

【讨论】:

    【解决方案2】:

    在 java 中,您需要有一个包含 main 方法的类才能运行。 main 方法是首先要运行的,您可以从中调用其他方法。您的类 Game 具有构造函数方法 Game()。要从您的 main 方法调用此方法,您应该在您的 main 方法中添加以下内容:

    new Game();
    

    【讨论】:

      【解决方案3】:

      嵌入 JavaFX 代码的 Swing 应用程序需要 main() 方法。

      https://docs.oracle.com/javafx/2/get_started/hello_world.html

      此链接可能有助于您解释此问题。

      【讨论】:

        猜你喜欢
        • 2013-01-29
        • 1970-01-01
        • 1970-01-01
        • 2016-07-29
        • 2017-08-26
        • 2016-09-03
        • 2018-03-29
        • 2014-06-20
        • 1970-01-01
        相关资源
        最近更新 更多