有人能告诉我为什么这在eclipse中有效,但在命令提示符中无效吗



我有三节课是作为作业从讲师那里得到的,在编辑它们之前,我试着编译它们。它们不会在命令提示符中引用引用"DrawPanel panel = new DrawPanel();"的"cannot find symbol error"进行编译。然后我试着在Eclipse中运行它,它运行得很好,关于为什么甚至如何在命令提示符中运行它的任何想法

TestDraw.java:

    package shapessimple;
    import javax.swing.JFrame;
    public class TestDraw
     {
        public static void main (String[]args)
     {
            DrawPanel panel = new DrawPanel();
            JFrame application = new JFrame();
            application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            application.add(panel);
            application.setSize(300,300);
            application.setVisible(true);
        }
    }
<小时>

DrawPanel.java:

package shapessimple;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JPanel;
public class DrawPanel extends JPanel {
    private Random randomNumbers = new Random();
    private MyLine[] lines;

    public DrawPanel() {
        setBackground(Color.white);
        lines = new MyLine[5 + randomNumbers.nextInt(5)];
        for (int count = 0; count < lines.length; count++) {
            int x1 = randomNumbers.nextInt(300);
            int x2 = randomNumbers.nextInt(300);
            int y1 = randomNumbers.nextInt(300);
            int y2 = randomNumbers.nextInt(300);
            Color color = new Color(randomNumbers.nextInt(256),
                    randomNumbers.nextInt(256), randomNumbers.nextInt(256));
            lines[count] = new MyLine(x1, y1, x2, y2, color);
        } 
    }
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (MyLine line : lines) {
            line.draw(g);
        }
    }
}
<小时>

MyLine.java:

package shapessimple;
import java.awt.Color;
import java.awt.Graphics;
public class MyLine {
    private int x1;
    private int y1;
    private int x2;
    private int y2;
    private Color myColor;
    public MyLine (int x1, int y1, int x2, int y2, Color color) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
        myColor = color;
    }
    public void draw (Graphics g) {
        g.setColor(myColor);
        g.drawLine(x1,y1,x2,x2);
    }
}

编辑:

它现在正在编译,但我得到了一个NoClassDefFoundError: TestDraw error message

为了运行应用程序,您需要编译所有使用的.java文件,而不是只编译"TestDraw.java"。确保每个源.java文件都有一个.class文件,并且它们都在sharpesimple文件夹中。

然后运行应用程序只需执行java shapesimple.TestDraw,它应该可以正常工作。

在从命令行运行程序之前,必须编译所有文件。要编译它,你必须包括所有的文件:

javac TestDraw.java DrawPanel.java MyLine.java

或者你可以做

javac *.java

然后,您应该能够通过运行包含main()的文件来运行程序,并指定类路径,以便类加载器知道在哪里查找:

java -cp . TestDraw

如果不设置类路径,那么类加载器将只使用CLASSPATH环境变量的值,该变量可能不包含包含程序的目录。

请注意,当运行.class文件时,不会包含.class扩展名。

如果您在Windows机器上运行,请转到shapessimple的父文件夹并尝试以下命令:

javac -cp ./:%CLASSPATH% shapessimple.TestDraw.java

或者在Linux机器上:

javac -cp ./;$CLASSPATH shapessimple.TestDraw.java 

相关内容

最新更新