gpt4 book ai didi

java - JPanel位置问题

转载 作者:行者123 更新时间:2023-11-30 03:00:21 26 4
gpt4 key购买 nike

我必须创建一个 GUI,并且我真的很想为其设置背景。为了做到这一点,我创建了一个名为“Backround”的类,在其中使用了paintComponent 方法。我给了它我想要在背景上设置的文件并且它起作用了。

这是我的背景类:

public class Background extends JPanel
{
public void paintComponent(Graphics g)
{
try {
Image img = ImageIO.read(new File("./fond.jpg"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}

catch (IOException e) {
e.printStackTrace();
}
}
}

但是,一旦图像位于背景上,框架上的面板就不再位于同一位置,我真的不知道如何解决这个问题,而且仍然没有找到任何与此相关的主题。

这是我在类里面描述 GUI 的一段话:

    this.setContentPane(new Background());

this.setTitle("Arena");
this.setSize(800, 500);
this.setLocationRelativeTo(null);
//this.setLayout(new FlowLayout(FlowLayout.CENTER));
//this.setLayout(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setVisible(true);


// ******************************************** PANEL 1 ******************************************

Panel P1 = new Panel();
this.add("NORTH", P1);
P1.setLayout(new FlowLayout());
P1.add(new Label ("Joueur 1"));
P1.add(new Label ("Action"));
P1.add(new Label ("Joueur 2"));
//P1.setVisible(true);


// ********************************************* PANEL 2 ******************************************


Panel P2 = new Panel();

P2.setLayout(new FlowLayout());

P2.add(Liste1);

// Boutons
Button B1 = new Button("FIGHT");
P2.add(B1);
Button B2 = new Button("HEAL");
P2.add(B2);

P2.add(Liste2);
this.add("WEST", P2);
// P2.setVisible(true);

此外,当我删除对后台构造函数的调用时,面板将返回到其初始位置。

我希望你能帮助我或重定向我!

谢谢!

安托万·斯伯特

最佳答案

  1. 确保在执行任何客户绘制之前调用 super.paintComponent
  2. 不要在paint方法中加载资源(如图像),这会对程序的性能产生影响
  3. JPanel 默认情况下使用 FlowLayout,但在将 Background 面板应用为 contentPane< 后,您永远不会更改布局。调用 setContentPane 后,使用 setLayout(new BorderLayout()) 或在类构造函数中应用布局(在加载图像的同时)
  4. 确保在建立基本 UI 后最后调用 setVisible

关于java - JPanel位置问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36163844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com