gpt4 book ai didi

Java图像显示问题

转载 作者:行者123 更新时间:2023-11-30 07:14:58 26 4
gpt4 key购买 nike

亲爱的 stackoverflow 的好人

我的一群 friend 正在尝试用 Java 制作关卡编辑器。

我们有一个 Jpanel 而不是 Jframe,我们正在尝试从保存为字符串的文件路径将小图像放到 Jpanel 上。最后,我们想要一个您可以直接拖放的图像列表。到目前为止,我们已经尝试了几种方法,但都没有成功。

我们可以加载图像,但是我们无法让这些图像实际显示,解决上述问题的最佳方法是什么?

下面是我们目前所拥有的示例。

EnemyPlacementGrid = new JPanel();
EnemyPlacementGrid.addMouseListener(new MouseAdapter() {
//@Override
public int mouseX;
public int mouseY;
public void mouseClicked(MouseEvent arg0) { //what happens when you click in the EnemyPlacementGrid
System.out.println("Correct Area for placement");
mouseX = arg0.getX();
mouseY = arg0.getY();
//System.out.println("X:" + mouseX + ", Y:" + mouseY );
Enemy newEnemy = workingEnemy.cloneSelf();
newEnemy.setLocation(mouseX, mouseY);
System.out.println("newEnemy object: " + newEnemy);
System.out.println(newEnemy.weaponList);
currentWave.addEnemy(newEnemy);
System.out.print(currentLevel);
}
});

非常感谢任何帮助。

更新:

截至目前,我有一张图片出现,但我无法更新该图片。注意代码如下:

public void run() {
try {
BufferedImage img = ImageIO.read(new File(IMG_PATH));
ImageIcon icon = new ImageIcon(img);
WaveScreen frame = new WaveScreen();

JPanel panel = (JPanel)frame.getContentPane();
JLabel label = new JLabel();
label.setIcon(new ImageIcon("images/map_on.png"));// your image here
panel.add(label);


frame.setVisible(true);
panel.add(label);
panel.repaint();

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

更新,从评论中尝试的方法:

Graphics2D g = null;
Graphics2D g2 = (Graphics2D)g;
Image imageVariable = new ImageIcon("images/map_on.png").getImage();
g.drawImage(imageVariable, mouseX, mouseY, null);

最佳答案

好吧,我想尝试使用 Graphics,这意味着您需要覆盖 paint 方法;我建议您将 mouseX 和 mouseY 作为全局变量……

// creating global image variable for use later
Image imageVariable = new ImageIcon("image path").getImage();

public void paintComponent(Graphics g) {
// here you could either create a Graphics2D object
// Graphics2D g2 = (Graphics2D)g;
// or you could use the g parameter as it is, doesn't matter.
// use the global variable for the image to be drawn onto the screen
// use the global value of the mouseX and mouseY for where you click the mouse
// to place the image, and this should be it
g.drawImage(imageVariable, mouseX, mouseY, null);
}

希望这对您有所帮助!

关于Java图像显示问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18167628/

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