Lozansky
Lozansky

Reputation: 374

How to correctly create and import packages in Java

I am using Netbeans 8.1 and Java 8.

I have a Java program named "MyFrame.java" and I want to create a package with its classes and methods - I call this package "myframe" and it is located at "\Lab\MyFrame\src\myframe". See picture: enter image description here

(Ignore the red lines - this is a dummy version).

The class file is created after compiling, using the command "javac MyFrame.java", in the same directory \myframe. Now I want to import the package "myframe" in a new Java file "MoreButtons.java". So it would look like this and for convenience I save it in \src: enter image description here

Compiling and executing MoreButtons.java works fine. The package has been imported. But now MyFrame.java is a bit trickier to execute: the naïve approach yields: enter image description here

Translation: Error: Could not find or load main class This seems to be quite a common problem and one of the solutions is simply to add the directory (\myframe) to the PATH environment variable. However, doing this still produced the error.

1) What am I doing wrong and how can I fix this?

2) What is the correct way to create and import custom-made packages in Java?

Upvotes: 0

Views: 100

Answers (1)

user2575725
user2575725

Reputation:

Make sure that terminal is at path Lab\MyFrame\src:

javac myframe\MyFrame.java MoreButtons.java
java -cp .; myframe.MyFrame

P.S. (/,:=linux/mac) or (\,;=windows) output 1 output 2

MyFrame.java

package myframe;

public class MyFrame extends javax.swing.JFrame{

    public MyFrame(String title){
        super(title);
        setSize(200,100);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }
}

MoreButtons.java

public class MoreButtons {
    public static void main(String[]args){
        new myframe.MyFrame("More Buttons");
    }
}

Upvotes: 1

Related Questions