user35359
user35359

Reputation: 253

Class not found Error when executing a simple jar file

I am learning Java and trying to make a very simple program with Swing work. I use the command line java tools.

I have a single java file with this content:

import javax.swing.*;
import java.awt.*;

public class MyClass {

    public static class MyActLst implements java.awt.event.ActionListener {
       public void actionPerformed(java.awt.event.ActionEvent e)
       {
           System.out.println("Action occured.\n");
       }
    }

    public static void main(String[] args) {
        JFrame f = new JFrame("Example");
        f.setSize(640,480);
        f.setLayout(null);

        JButton b = new JButton("OK");
        b.setBounds(0,0,100,100);
        b.setText("Test");

        MyActLst myActLst = new MyActLst();
        b.addActionListener(myActLst);
        f.add(b);

        f.setVisible(true);
    }
}

The filename is MyClass.java. When I compile this using "javac MyClass.java" and then run with "java MyClass", it works. However, when I try to make a .JAR file, using "jar cmf MyClass.mf MyClass.jar MyClass.class MyClass.java" and then try to execute it using "java -jar MyClass.jar", I get an error message:

Exception in thread "main" java.lang.noClassDefFoundError: MyClass$MyActLst
at MyClass.main(MyClass.java:25)[...]

It seems like the inner class MyActLst was not found. What puzzles me is that it is found when I simply compile the .java file by itself.

MyClass.mf looks like this:

Manifest-Version: 1.0
Main-Class: MyClass

This is my first time trying to make a .jar file, so I'm sorry if this is a trivial question.

Upvotes: 0

Views: 114

Answers (1)

After compilation you have two files MyClass$MyActLst.class and MyClass.class. You must integrate this two files. You can use "jar cmf MyClass.mf MyClass.jar *.class MyClass.java"

Subclass are generated in different files.

Upvotes: 1

Related Questions