有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

运行简单swing程序时出现java错误

我刚开始学荡秋千。我想尝试一个简单的程序,但我不能运行它

import java.awt.*;
import javax.swing.*;
class MyDrawPanel extends JPanel 
{
    public void paintComponent(Graphics g) 
    {
        g.setColor(Color.orange);
        g.fillRect(20,50,100,100);
    }
}

我得到以下错误:

Exception in thread "main" java.lang.NoSuchMethodError: main

我的问题:我们是否需要在每个想要运行的类中都有一个main方法?JVM不能运行任何没有主方法的类。这里我不需要一个主类,因为这个paintComponent方法应该由系统调用,对吗

附言:我正在使用普通的香草cmd来编译和运行


共 (4) 个答案

  1. # 1 楼答案

    java相当简单,当您给它一个类文件时,它将加载它并尝试执行一个程序。Java程序定义为在“publicstaticvoidmain(String…args)”方法中启动。因此,缺少此函数的类文件没有程序的有效入口点

    要使java调用paintComponent()方法,必须将类的实例添加到顶级容器(如JFrame)或web应用程序的JApplet中。(小程序不使用main方法,因为它们是作为网页的一部分而不是独立应用程序执行的。)

    例如:

    import javax.swing.*
    public class MyDrawPanel{
         public static void main(String... args)
         {
             JFrame frame = new JFrame(200,200);//A window with 200x200 pixel
             MyDrawPanel mdp = new MyDrawPanel();//Panel instance
             frame.add(mdp);//Add the panel to the window
             frame.setVisible(true);//Display all
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit when the window is closed
    
         }
    }
    
  2. # 2 楼答案

    Do we need to have a main method in every class we want to run?

    您需要一个带有main方法的类来启动JVM

    Can't JVM run any class which doesnt have a main method.

    不是一开始

    Here i don't require a main class i think, cuz this paintComponent method should be called by the system, right?

    错。的确,paintComponent()方法最终将被“系统”调用,特别是Swing事件调度线程。但这需要首先开始,当您创建一个窗口并使其可见时,这会隐式地发生。而这反过来只能发生在主方法中

  3. # 3 楼答案

    在要为其运行程序的类中需要一个main方法。这是强制性的。如果有多个方法,JVM如何知道应该调用哪个方法来启动。他们可以猜测,但大多数时候,猜测可能会出错。所以,提供一个简单的主方法会有所帮助

  4. # 4 楼答案

    正如沃德康所说,您需要一个“main”方法。确保它看起来像这样:

    public static void main(String[] args)
    {
      // your code here.  
      // this example will use your panel:
    
      // create a new MyDrawPanel 
      MyDrawPanel panel = new MyDrawPanel();
    
      // create a frame to put it in
      JFrame f = new JFrame("Test Frame");
      f.getContentPane().add(panel);
    
      // make sure closing the frame ends this application
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
      // show the frame
      f.setSize(100,100);
      f.setVisible(true);
    
    }
    

    是的,您要运行的每个Java程序都需要一个具有此签名的main方法:

      public static void main(String[] args)
    

    您可以在其他系统(如web服务器等)中运行java代码,但要简单地运行它,main是入口点。把它放在任何你想启动程序的地方

    运行时,请确保类名正确,以帮助它找到主方法。在您的情况下,如果您在MyDrawPanel所在的目录下手动运行java。类文件,您可以执行以下操作:

      java -cp . MyDrawPanel
    

    如果您是从开发人员工具内部运行的,那么它将提供一种运行您正在查看的类的方法