This is more like a package/import test. We’ll start with my base folder at …/javaf/test.java
My goal is to create subcategory and create a class with a button that I can import to test.java when I need a button. I feel like I’ve done it right, I know that the button doesn’t do anything as of now, but I just want to make the whole thing work and expand the code thereafter. So here goes – This is test.java
import paket.*; // importing classes from subcategory paket!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class test {
public test() {
JFrame myFrame;
JPanel myPanel;
myFrame = new JFrame("Hello FramWorld");
myPanel = new JPanel();
// Here I want to add the object created in paket/myButts.java
// The problem is how to make these two lines work.
myButts myButton = new myButts();
myPanel.add(myButton);
myFrame.setVisible(true);
myFrame.getContentPane().add(myPanel, BorderLayout.CENTER);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
}
public static void main(String args[]) {
new test();
}
}
And here is my …/javaf/paket/myButts.java
package paket; // Here is the package function (ought to work like a link)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
// This class should only create a button.
public class myButts {
public myButts() {
JButton myButt = new JButton();
}
}
I’ve compiled myButts.java with no errors. But then I compile test.java and it gives me the following error:
test.java:19: cannot find symbol
symbol : method add(paket.myButts)
location: class javax.swing.JPanel
myPanel.add(myButton);
Thanks for reading,
Z
I think you want:
If you want to add instances of your class directly to Swing controls, it must extend a Swing or AWT type (in this case JButton).
Before, you just created a local JButton in the constructor, which was unused and inaccessible everywhere else.
As a note, it’s best to try to follow the Java style guide, in particular naming conventions. Classes are recommended to be mixed case, e.g. MyButton.