Daniel Daniel - 7 months ago 31
Java Question

Switching between JPanel Forms in Java Frame

I am struggling with JPanels. I would like to have 1 Frame where i put 1 MainJPanel and then I add some JPanel Forms setting it as a source for my MainJPanel.
Then to switch between JPanel Forms

I've got this in my Main.java Frame:

public class Main extends javax.swing.JFrame {
PanelForm1 p1 = new PanelForm1();
PanelForm2 p2 = new PanelForm2();
GridBagLayout layout = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();

public Main() {
initComponents();
MainJPanel.setLayout(layout);
c.gridx = 0;
c.gridy = 0;
MainJPanel.add(p1,c);
c.gridx = 0;
c.gridy = 0;
MainJPanel.add(p2,c);
m.p1.setVisible(true);
m.p2.setVisible(false);
}
}


And in PanelForm1.java my ButtonClick trying to show Panel2Form.

public class Panel1 extends javax.swing.JPanel {

public Panel1() {
initComponents();
}

private void ButtonGoToPanel2ActionPerformed(java.awt.event.ActionEvent evt) {
Main m = new Main();
m.p1.setVisible(false);
m.p2.setVisible(true);
}
}


Panel2Form.java is likely the same.

The only way I can do it is to have buttons right in Main.java, but I don't want to have buttons, which are always visible.

I know, that when I'm creating an Class Object
Main m = new Main();
I a new copy of
p1
and
p2
etc., so I am not changing anything.

Can anybody help? Or there is another, better way to do this?
I don't want to have everything in one file, because it won't be clear, and also every method like CardLayout won't go, because I don't want always to have buttons to switch JPanel Forms.

Answer

Then to switch between JPanel Forms

So you should be using a CardLayout. See the section from the Swing tutorial on How to Use CardLayout for working examples.

The only way I can do it is to have buttons right in Main.java, but I don't want to have buttons, which are always visible

Well, the panel won't switch on its own so you need to handle some kind of event to initiate the swapping of panels:

  1. user clicks a menu item
  2. user clicks a button
  3. user enters a key stroke
  4. the application switches panels

Then you pass a parameter from the child panel up to the main panel indicating which panel you want to display.

I don't want to have everything in one file, because it won't be clear

There is no need to have everything in one file. The child panels will need to have access to the parent panel.

One way to do this is pass parameters:

JPanel main = new JPanel();
JPanel child1 = new ChildPanel(main);
main.add(child1);
JPanel child2 = new ChildPanel(main);
main.add(child2);

and also every method like CardLayout won't go, because I don't want always to have buttons to switch JPanel Forms

Yes, you can use a CardLayout. No you don't need buttons. All you need is the "panel name" you want to display. Then you notify the panel with the CardLayout.