如何在 Java 中堆叠/覆盖 jPanel? [英] How can I stack/overlay jPanels in Java?
问题描述
我对 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屋!