如何在Java中堆叠/覆盖jPanel? [英] How can I stack/overlay jPanels in Java?

查看:633
本文介绍了如何在Java中堆叠/覆盖jPanel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很喜欢Java中的GUI编程,我做了很多研究,但我找不到这个问题的答案。

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.

我有一个简单的 JFrame 带有菜单,并且在 JFrame 里面我有 JPanel 使用登录表单(用户输入他们的用户名和密码),然后我想将 JPanel 更改为另一个 JPanel 取决于用户想要做什么。

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.

这样做的最佳方法是什么?我认为堆叠 JPanels 是可以的。但是在Netbeans中添加新的 JLayeredPanels 后,它们不会堆叠。我在某处读到了我应该使用Z排序或类似的东西,但我在设计师的视图中找不到它。

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 类有一个有用的API,可以满足您的要求。使用 next(),first(),last()等方法会很有帮助。
我已准备好在父面板和/或框架内更换面板的简单演示。
看看它:

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

这篇关于如何在Java中堆叠/覆盖jPanel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆