Eclipse 找不到主类

标签 eclipse java

我在安装了 OpenJDK 7 的 Ubuntu 12.04 上使用 Eclipse 3.7.2

java -version 给出

java version "1.6.0_24"
OpenJDK Runtime Environment (IcedTea6 1.11.1) (6b24-1.11.1-4ubuntu3)
OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode)

每当我尝试运行项目时,都会收到以下错误。

Exception in thread "main" java.lang.NoClassDefFoundError: test/Example
Caused by: java.lang.ClassNotFoundException: test.Example
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: test.Example. Program will exit.

我在 Windows 系统上成功编译的所有项目都会发生这种情况。 而且,当直接从终端使用 javac 和 java 时,它可以工作。 有简单的解决方案吗?这是因为 OpenJDK 的原因吗?

类代码是:

package test;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Example extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public Example() {
       setTitle("Simple example");
       setSize(300, 200);
       setLocationRelativeTo(null);
       setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Example ex = new Example();
                ex.setVisible(true);
            }
        });
    }
}

更新:我的源代码位于名为 swingtest 的文件夹中。在调试时,我发现 Eclipse 使用源的类路径为 swingtest/swingtest/src/test/而不是 swingtest/src/test/。这个问题可以纠正吗?

最佳答案

此错误可能由于以下原因而发生

  1. 可能缺少依赖项/必需的 jar。 要查找 jar 是否丢失,请单击项目->Java 构建路径->源 在顶部,您可以看到错误消息 xyz.jar 丢失。 因此,通过单击添加外部 jar 选项来添加特定的 jar

  2. 可能是java类路径没有设置。 因此,在 Eclipse 和环境设置中配置 JDK 类路径

  3. 尝试清理项目并查看是否已修复

关于Eclipse 找不到主类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11381793/

相关文章:

java - 在 fragment 的 onCreateOptionsMenu() 中使用 getActivity() 偶尔会抛出 NPE

eclipse - 相当于eclipse中intelliJ的Ctrl + Shift + A?

java - RCP 导出的 EXE 显示 java 控制台

java - Eclipse如何不调试jar文件

java - 使用@WebService的 `endpointInterface`属性时如何隐藏Web服务中的接口(interface)方法?

c# - 多语言开发

java - 当我尝试安装 SVN Connector 时,出现以下错误。我用的是 eclipse NEON

android - 在 Android 上设置 MonkeyRunner

Android:2.1 并为 2.2+ 用户安装 SD 卡功能

java - 不同阶层的共享偏好不起作用