使用JLayeredPane将多个JPanel添加到一个JPanel [英] Using JLayeredPane to add multiple JPanels to a JPanel

查看:416
本文介绍了使用JLayeredPane将多个JPanel添加到一个JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将多个面板添加到另一个面板.我希望它们彼此重叠,所以我正在使用JLayeredPane.我为每个按钮都添加了一个按钮.工作时应出现两个按钮.

I am trying to add multiple panels to another panel. I want them to be on top of each other so I'm using JLayeredPane. I've added a button to each one. Two buttons should appear when it works.

import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

public class PanelTest {
public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel mainPanel = new JPanel();
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();

    JLayeredPane layers = new JLayeredPane();
    mainPanel.add(layers);

    panel2.setOpaque(false);
    panel1.setOpaque(false);
    panel1.setVisible(true);
    panel2.setVisible(true);

    panel1.add(new JButton("1111111111"));
    panel2.add(new JButton("2"));

    frame.setContentPane(mainPanel);
    layers.add(panel1, new Integer(2));
    layers.add(panel2, new Integer(3));

    frame.setVisible(true);
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

仅可见mainPanel的灰色背景.我在做什么错了?

Only the grey background of the mainPanel is visible. What am I doing wrong?

推荐答案

将组件添加到JLayeredPane时,实际上是使用容器将组件添加到空布局中.这意味着您必须完全指定组件的大小和位置,并且经常使用setBounds(...)调用来解决这两个问题.在panel1和panel2上调用它,例如:

When adding a component to a JLayeredPane, you're essentially adding the component to a null layout using container. This means that you must fully specify both the component's size and its position, often solving both with a setBounds(...) call. Call this on panel1 and panel2, for example:

panel1.setBounds(10, 10, 100, 100);
panel2.setBounds(70, 70, 100, 100);

设置界限没有任何作用

setting bounds didn't make any difference

需要设置大小(界限),但是仍然存在其他问题.

Setting the size (bounds) is required but you still have an additional problem.

您正在将JLayeredPane添加到使用FlowLayout的JPanel中.默认情况下,FlowLayout遵守添加到其中的组件的首选大小.由于JLayeredPane使用空布局,因此其首选大小为(0,0),因此无需绘制任何内容.

You are adding the JLayeredPane to a JPanel which uses a FlowLayout. By default a FlowLayout respects the preferred size of the component added to it. Since JLayeredPane uses a null layout its preferred size is (0, 0) so there is nothing to paint.

两种解决方案:

  1. 您不需要JPanel,只需使用:frame.setContentPane(layers);
  2. 如果您确实要使用面板,则需要更改布局管理器:JPanel mainPanel = new JPanel( new BorderLayout());
  1. You don't need the JPanel, just use: frame.setContentPane(layers);
  2. If you really want to use the panel then you need to change the layout manager: JPanel mainPanel = new JPanel( new BorderLayout());

这篇关于使用JLayeredPane将多个JPanel添加到一个JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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