JFrame中的图像相互覆盖,而不是相互显示两个图像

2022-01-24 00:00:00 user-interface java swing jframe
public class Board extends JFrame
{
     public void bd()
{


    JFrame frame=new JFrame();
    JLabel background1 = new JLabel(new ImageIcon("background.png"));
    JLabel knight=new JLabel(new ImageIcon("knight.jpg"));
    frame.add(background1);
    frame.add(knight);
    frame.pack();
    frame.setResizable(false);     
    frame.setVisible(true); 





    }
}

我的代码遇到了一些问题

I've been having some trouble with my code

当我添加骑士图像时,背景图像将消失,只有骑士图像出现.我如何使图像重叠或使背景图像像背景一样

when i add the knight image the background image will disappear and only the knight image appears. How would i make the images overlap or make the background image act like a background

推荐答案

JLabel background1 = new JLabel(new ImageIcon("background.png"));
JLabel knight=new JLabel(new ImageIcon("knight.jpg"));
frame.add(background1);
frame.add(knight);

我猜您真正想要的是将骑士显示在顶部(在 z 轴上),因此您需要执行以下操作:

I'm guessing what you really want is have the knight displayed on top (on the z axis) so you need to do something like:

JLabel background1 = new JLabel(new ImageIcon("background.png"));
background.setLayout( new BorderLayout() );
JLabel knight=new JLabel(new ImageIcon("knight.jpg"));
background1.add(knight);
frame.add(background1);

也就是说,您需要遵循父/子层次结构:

That is you need to follow a parent/child hierarchy:

  1. 为框架添加背景
  2. 将骑士添加到背景中

相关文章