Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
840 views
in Technique[技术] by (71.8m points)

swing - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...