gpt4 book ai didi

java - 更改绘画面板中的绘画图像

转载 作者:太空宇宙 更新时间:2023-11-04 15:11:56 24 4
gpt4 key购买 nike

我试图通过将新图像目录发送到我的绘画面板,然后将图像变量更改为该图像来更改正在绘制的图像。我已经测试了代码以确保目录能够通过,但图像永远不会改变。他们似乎只是忽略了新的图像并继续绘制前一个图像。我对困惑的代码表示歉意,但我已经调整了几个小时,试图改变图像,但我感到很沮丧。

public class painting extends JPanel {
private String BGDir;
private String Dir;
private int Width;
private int Height;
private Image image1;
private Image image2;

public painting(int h, int w, String BG, String Char) {
BGDir = BG;
Dir = Char;
Height = h;
Width = w;
System.out.println(BGDir);
System.out.println(Dir);
try {
image1 = (new ImageIcon(Char)).getImage();
image2 = (new ImageIcon(BG)).getImage();
} catch (Exception e) {
System.out.println("no such file");
}
repaint();
}

public void update(Graphics g) {
paintComponent(g);
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
System.out.println(BGDir);
System.out.println(Dir);
// PAINTS THE BACKGROUND
g2.drawImage(image2, 0, 0, getWidth(), (int) (getWidth() * .533), null);
// PAINTS THE SCALED CHARACTER
g2.drawImage(image1, (int) (Width / 6.22), (int) (Height * .246),
(int) (Height * .754 * .2376), (int) (Height * .754), null);
repaint();

}
}

最佳答案

我使用 BufferedImage,但这是我拥有的工作代码的示例。

public class PaintPanel extends JPanel {

private static final long serialVersionUID = 1L;

BufferedImage icon;

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(getBufferedIcon(), 12, 12, null);
}

public void setBufferedIcon(BufferedImage icon) {
this.icon = icon;
}

private BufferedImage getBufferedIcon() {
return icon;
}
}

忽略 12 的偏移量,那只是因为我从我的一个项目中复制了它。我在另一个类中所做的就是创建 PaintPanel 并设置 BufferedIcon

每次我想更新图标时,我都会调用PaintPanel.setBufferedIcon(icon);,然后调用PaintPanel.repaint();

请记住为PaintPanel命名,我只是这么调用它,以便您可以更轻松地阅读代码:)

关于java - 更改绘画面板中的绘画图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21238719/

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