Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stack/overlay jPanels in Java?

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!

like image 766
Pacha Avatar asked Feb 22 '23 09:02

Pacha


1 Answers

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);
    }
}
like image 120
Juvanis Avatar answered Mar 03 '23 18:03

Juvanis