且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用JLayeredPane将多个JPanel添加到一个JPanel

更新时间:2023-12-04 23:51:22

将组件添加到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());