为什么主要方法不运行?

关于Java中的public static void main方法有点困惑,并希望有人可以提供帮助。 我有两节课

public class theGame { public static void main(String[] args) { lineTest gameBoard = new lineTest(); } 

 public class lineTest extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.red); g2d.drawLine(100, 100, 100, 200); } public static void main(String[] args) { lineTest points = new lineTest(); JFrame frame = new JFrame("Points"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(points); frame.setSize(250, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } } 

不幸的是,我的程序没有绘制线。 我试图弄清楚为什么lineTest类中的main方法没有启动?

虽然我可以通过将main方法更改为其他内容(例如’go’然后从’theGame’类运行该方法)来使其工作,但我很感兴趣为什么lineTest类中的main方法不起作用。

您的应用程序有一个入口点,该入口点是执行的单个主要方法。 如果您的入口点是theGame类,则只执行该类的main方法(除非您手动执行其他类的main方法)。

创建lineTest类的实例不会导致其main方法被执行。

我在下面开始了。 看起来您可能希望花一些时间来学习更基本的Java教程或课程,以便快速掌握基本的Java知识。

下面的代码中发生的是theGame类有一个程序的主条目。 JVM将在程序开始时调用main方法。 从那里,它将执行您给出的指令。 所以大多数时候,两个主要方法在单个项目中没有意义。 此规则的例外情况是,您希望在同一程序中有两个单独的应用程序入口点(例如,命令行应用程序和使用相同逻辑但控制方式不同的GUI应用程序)。

因此,使用下面的代码,您必须在为此应用程序启动JVM时将TheGame类指定为主入口点。

 public class TheGame { private final LineTest theBoard; public TheGame() { theBoard = new LineTest(); } public void run() { JFrame frame = new JFrame("Points"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(theBoard); frame.setSize(250, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } /** * Main entry for the program. Called by JRE. */ public static void main(String[] args) { TheGame instance = new TheGame(); instance.run(); } } 

 public class LineTest extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.red); g2d.drawLine(100, 100, 100, 200); } } 

执行java应用程序时,通过在一个特定类上调用main方法来执行它。 这个主要方法将是选择执行的类中的主要方法。

在您的情况下,您选择在theGame类上执行main方法。

当在应用程序中构造另一个类时,该类的构造函数会自动执行,但该类上的main方法不会自动执行。