Issue
Using NetBeans IDE and Java, neither of which I'm overly familiar with. I have a JFrame laid out with a JPanel on it, and said JPanel has buttons on it. This JPanel is in the JFrames class. When one of these buttons is clicked, I would like to stop displaying this JPanel, and display another JPanel in a different class. I am using the GUI designer hence the panels being in different classes.
The buttonclick event in the JFrame class for one of the buttons I have:
private void buttonActionPerformed(ActionEvent e) {
panel1.setVisible(false);
Panel2 panel2 = new Panel2();
this.add(panel2);
panel2.setVisible(true);
This produces results of the panel1 disappearing however leaving a blank Jframe as panel2 does not display.
I have looked at CardLayout but I need the buttons on the panels to issue commands rather than buttons on another panel swapping around panels of a CardLayout.
EDIT: Have rewritten question to actually provide context and not just "help pls" as I've been told that what I was asking was too broad, which is completely correct. I've only just started learning Java so if this is still to broad aquestion, apologies.
Solution
Lets try to help a bit here ...
First of all, it is not a good idea to do more than "almost" nothing in action listener code. Especially instantiating a new panel object within that listener is a bad idea.
A more reasonable approach: create all your panel objects up front. Like: when your application comes up, maybe have a list of the required panel objects. And then, within your action listener code, simply add the one that needs to show up, and remove the one that isn't required any more.
Also note:
- anything you "do" within an action listener happens on the event dispatcher thread (go google that term). here, that is probably what you want, but very often, it is not.
- just calling setVisible() isn't enough. You might have to trigger the layout manager to do a repaint. Thus decide for a specific layout manager, and research that dynamically adding/hiding of components.
Answered By - GhostCat
Answer Checked By - Candace Johnson (JavaFixing Volunteer)