I've written a standard console application (web scraping) with several classes. The only thing that main fucntion does, is: - create one instance of a class - call one method from created object
Now I need to add the simplest GUI which will contain one button to perform second of those aforementioned actions (call method) and textarea to display everything that NetBeans output shows now.
I created new file with GUI class. It's basically a jFrame with jButton and jTextArea. I managed to get text output to work like I assumed. However I have no idea how to set the button. Netbeans creator redirects me to this part of code:
private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
p1.use(); // <<< my initial try
}
where p1 is object created in main class in original file. Netbeans marks "p1" as "cannot find symbol" which is understandable. However, how can I perform such a simple operation? I basically need that Button to push the program forward.
You need to pass the p1 object from your main class into the class for your GUI through a constructor or setter, otherwise it doesn't know what you're trying to access.
For example,
public class MainClass {
private MyGuiClass gui;
private P1Class p1;
public static void main(String[] args) {
p1 = new P1Class( /*arguments*/ );
gui = new MyGuiClass( p1, /*other arguments*/ );
}
// Other logic...
}
public class MyGuiClass extends JFrame {
private P1Class p1;
public MyGuiClass( P1Class p1, /*other arguments*/ ) {
this.p1 = p1;
}
// Other logic...
}
At this point, you can refer to the p1 object in the rest of your code.
There are many ways to achieve that.
Scenario 1
Make the object p1 accessible to the jFrame object by making it static in the Main class.
public class Main {
public static P1 p1;
public static void main(String[] args) {
p1 = new P1();
//open window etc.
}
}
public class MyFrame extends JFrame {
private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
// Access object by static reference
Main.p1.use();
}
}
Scenario 2
You can pass the object P1
as a parameter to the constructor of your jFrame object.
public class Main {
public static void main(String[] args) {
P1 p1 = new P1();
new MyFrame(p1);
//open window etc.
}
}
public class MyFrame extends JFrame {
private P1 p1;
public MyFrame(P1 param) {
// Save object inside the JFrame object
this.p1 = param;
}
private void buttonActionPerformed(java.awt.event.ActionEvent evt) {
p1.use();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.