I am really new to GUI programming in Java, I did a lot of research and I couldn't find an answer to this problem.
I have a simple JFrame
with a menu, and inside this JFrame
I have a JPanel
with a log in form (were users input their username and password), and then I want to change that JPanel
to another JPanel
depending on what users want to do.
What would be the best way of doing this? I think that stacking JPanels
is OK. But after I add new JLayeredPanels
in Netbeans they don't stack. I read somewhere that I should use Z ordering or something like that, but I can't find it on the designer view.
Well, thank you very much for your patience!
CardLayout
class has a useful API that can serve your requirements. Using methods like next(), first(), last()
can be helpful.
I've prepared a simple demonstration of changing panels within a parent panel and/or frame.
Take a look at it:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanelChanger implements ActionListener
{
JPanel panels;
public void init(Container pane)
{
JButton switcher = new JButton("Switch Active Panel!");
switcher.addActionListener(this);
JPanel login = new JPanel();
login.setBackground(Color.CYAN);
login.add(new JLabel("Welcome to login panel."));
JPanel another = new JPanel();
another.setBackground(Color.GREEN);
another.add(new JLabel("Yeah, this is another panel."));
panels = new JPanel(new CardLayout());
panels.add(login);
panels.add(another);
pane.add(switcher, BorderLayout.PAGE_START);
pane.add(panels, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent evt)
{
CardLayout layout = (CardLayout)(panels.getLayout());
layout.next(panels);
}
public static void main(String[] args)
{
JFrame frame = new JFrame("CardLayoutDemo");
PanelChanger changer = new PanelChanger();
changer.init(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With