Java图像显示问题

时间:2013-08-11 00:31:05

标签: java image swing graphics jpanel

亲爱的stackoverflow人员

我的一群朋友正试图用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);

2 个答案:

答案 0 :(得分:2)

好吧,我想尝试使用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);
}

希望这有帮助!

答案 1 :(得分:2)

如果游戏很简单,user2277872的解决方案将起作用,您可以使用java中的graphics2D。但是,如果您正在计划更复杂的游戏(大量交互,大量纹理),那么2D图形的默认Java框架将被证明太慢。

如果您计划开发这样的游戏,我强烈建议您学习OpenGL或使用现有的图形框架,例如

JMonkeyEngine(http://jmonkeyengine.com/) 要么 光滑(http://slick.cokeandcode.com/index.php

更多信息:What should I use to display game graphics?