Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile a .java file in Java?

I have the following code generated by Eclipse (.java file).

import org.eclipse.swt.widgets.Shell;

import org.eclipse.swt.widgets.Display;

public class HelloWorldSWT {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setText("Hello world!");
        shell.open();
        while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) display.sleep();
        }
        display.dispose();
    }

}

Now I want to compile the above file from the command line. I went to the directory where the source code is located and I tried two commands:
1. javac HelloWorldSWT.java
2. javac -d /home/myname/workspace/ HelloWorldSWT.java

In both cases I have the same error "The import org.eclipse cannot be resolved". /home/myname/workspace/ - is the directory where the class file is located.

As far as I understand the compiler does not see the org.eclipse.swt package. Why?

Can it be because the problematic package is located in "/home/myname/workspace/org.eclipse.swt/" (not in "/home/myname/workspace/org/eclipse/swt/")?

like image 605
Roman Avatar asked Feb 17 '10 09:02

Roman


2 Answers

You need to set your classpath so that the Java compiler knows where to find the org.eclipse.* classes. You can do that with a command line switch or an environment variable.

like image 138
benzado Avatar answered Sep 20 '22 10:09

benzado


Ok, Stephen C I did this job by hand. I used only Notepad++ (I promise)

  1. Start Notepad++ and create file HelloWorldSWT.java
  2. Copy example from author
  3. Save it!
  4. Open cmd and go to the directory with HelloWorldSWT.java
  5. Run the command javac HelloWorldSWT.java

  6. Ok, go to the Eclipse directory and find the correct jar swt-3.4.2-win32-win32-x86.jar

  7. Run this again

    D:\workspaces\spf_workspace\hand-made>javac -cp "D:\Program files\eclipse3_5\plugins\org.eclipse.swt.win32.win32.x86_3.5.1.v3555a.jar" HelloWorldSWT.java

All process take 2 minutes.

Don't try to run this:

`D:\workspaces\spf_workspace\hand-made>java -cp "D:\Program files\eclipse3_5\plugins\org.eclipse.swt.win32.win32.x86_3.5.1.v3555a.jar;." HelloWorldSWT`

Note: I add current dir . to classpath too.

like image 24
St.Shadow Avatar answered Sep 19 '22 10:09

St.Shadow