Reputation: 27
I am making an application for processing customer orders(in java).
My program has 3 JFrame
windows (Yes I know its not a good idea to use multiple frames, but they aren't really connected to each other).
JFrame
JFrame
After a Customer makes an order ( main frame > customer frame > complete order(button). I am doing something like this:
customerframe.dispose();
customerframe.revalidate();
customerframe.repaint();
reloadframe(); ///a method which reinitializes the frame (Note: I am doing a frame=new JFrame() here)
mainframe.setVisible(true);
I select customer again it opens the customerframe
but the problem is that the listeners don`t work anymore, I guess they somehow remain connected to the old frame or something.
I have been trying to make it work for some hours now...
Upvotes: 1
Views: 3859
Reputation: 1003
You should not be using multiple JFrames
See this link for more info.
Instead, I suggest you use a CardLayout as demonstrated here:
import javax.swing.*;
import java.awt.*;
public class MainFrame
{
static JPanel homeContainer;
static CardLayout cl;
JPanel homePanel;
JPanel otherPanel;
public MainFrame()
{
JFrame mFrame = new JFrame("CardLayout Example");
JButton showOtherPanelBtn = new JButton("Show Other Panel");
JButton backToHomeBtn = new JButton("Show Home Panel");
cl = new CardLayout(5, 5);
homeContainer = new JPanel(cl);
homeContainer.setBackground(Color.black);
homePanel = new JPanel();
homePanel.setBackground(Color.blue);
homePanel.add(showOtherPanelBtn);
homeContainer.add(homePanel, "Home");
otherPanel = new JPanel();
otherPanel.setBackground(Color.green);
otherPanel.add(backToHomeBtn);
homeContainer.add(otherPanel, "Other Panel");
showOtherPanelBtn.addActionListener(e -> cl.show(homeContainer, "Other Panel"));
backToHomeBtn.addActionListener(e -> cl.show(homeContainer, "Home"));
mFrame.add(homeContainer);
cl.show(homeContainer, "Home");
mFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mFrame.setLocationRelativeTo(null);
mFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mFrame.pack();
mFrame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(MainFrame::new);
}
}
With a Cardlayout, you switch between JPanel's instead. This way, you don't have to create a new JFrame, just to display new content. Basically, you have some sort of container, (Could be the JFrame
or could be a JPanel
) and then, when you add the other panels that you create, you give them a name. You can then switch between the panels using cardLayout.show(container, "Name");
Upvotes: 4