Reputation: 43
I am having trouble adding to a JFrame from another class. At runtime I initialise the JFrame and create it.
public static void main(String[] args) throws IOException {
Testing exc = new Testing();
exc.MessagingGUI();
Update.Server();
Scanner input = new Scanner(System.in);
String some_text = input.nextLine();
exc.AddPanel();
}
public void MessagingGUI() throws IOException {
JPanel welcome = new JPanel();
JLabel title = new JLabel("Stuff");
welcome.add(title);
tab.add("Home", welcome);
pane.add(tab);
Messaging.setTitle("Messaging");
Messaging.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Messaging.setContentPane(pane);
Messaging.setVisible(true);
Messaging.pack();
System.out.println("Done");
}
And then this runs in a different class.
public class Update {
public static void Server() {
System.out.println("Hello");
Testing exc =new Testing();
exc.AddPanel();
}
}
Now I know that it's because the Update class can't access the JFrame but I don't know why. It's not the AddPanel method because if you enter some text it works as it then allows the AddPanel method to run. So can someone explain how and why the Update class can't edit the JFrame. Thanks
Upvotes: 1
Views: 109
Reputation: 285405
It's because you haven't given the Update class a sufficient reference to the viewed GUI. You need to make your server method non-static and pass in a valid reference to the Testing GUI into the Update constructor:
public class Update {
private Testing exc;
public Update(Testing exc) {
this.exc = exc;
}
// this shouldn't be static
public void server() {
System.out.println("Hello");
// Testing exc =new Testing(); // Nope!
exc.addPanel(); // rename to addPanel to comply with Java naming rules
}
}
When you create an Update instance, pass in a reference to the visualized Testing GUI. Then call the server method on the Update instance, not on the class since it is no longer static.
Upvotes: 1