Java中的图片拼图游戏

时间:2013-04-20 19:31:23

标签: java

这是我正在研究的高中项目。我找不到在画面上显示图像的方法。这是我的第一个问题。我相信将来我会有更多的问题。以下是我目前的代码。

第一部分:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JApplet;

public class GameVer2 extends JApplet implements ActionListener{
    private int sizeOfGame = 16;
    private ImageIcon[] picts = {new ImageIcon("back.png"),
    new ImageIcon("field.png"),new ImageIcon("front.png"),
    new ImageIcon("gym.png"),new ImageIcon("mermaid.png"),
    new ImageIcon("mickey_pirate.png"),new ImageIcon("path.png"),
    new ImageIcon("tweety.png"),new ImageIcon("back.png"),
    new ImageIcon("field.png"),new ImageIcon("front.png"),
    new ImageIcon("gym.png"),new ImageIcon("mermaid.png"),
    new ImageIcon("mickey_pirate.png"),new ImageIcon("path.png"),
    new ImageIcon("tweety.png")};

    private GamePiece[] tiles = new GamePiece[sizeOfGame];
    private int[] tilesReady;
    private int turn = 0;
    private GamePiece[] data = new GamePiece[2];

    public GameVer2(){
        this.setVisible(true);
        this.setLayout(new GridLayout(4,4));
        buildGamePieces();
    }

    public void buildGamePieces(){
        for(int i=0; i<tiles.length; i++){
            tiles[i] = new GamePiece(picts[i],i);
            this.getContentPane().add(tiles[i]);
            tiles[i].addActionListener(this);
            tiles[i].setActionCommand(i+"");
            this.getContentPane().add(tiles[i]);
            tiles[i].getImage();
        }
    }
    @Override
    public void actionPerformed(ActionEvent arg0){
        System.out.println("hello");
    }

    public void init(){
        GameVer2 go = new GameVer2();
    }
}

第二部分:

import javax.swing.ImageIcon;
import javax.swing.JButton;


public class GamePiece extends JButton{

    private ImageIcon image;
    private int id;

    //GamePiece b = new GamePiece("gym.png",1);
    //GamePiece c = new GamePiece("front.png",2);
    // b.match(c);

    public boolean match(GamePiece a){
        return this.getImage().toString().equals(a.getImage().toString());
    }

    public ImageIcon getImage(){
        return image;
    }

    public void setImage(ImageIcon image){
        this.image = image;
    }

    public int getID(){
        return id;
    }

    public void setId(int id){
        this.id = id;
    }

    public GamePiece (ImageIcon pict, int i){
        image = pict;
        id = i;
    }
}

1 个答案:

答案 0 :(得分:0)

setIcon添加到构造函数方法中,然后相应地更改。

  public GamePiece (ImageIcon pict, int i){
        setIcon(pict);
    }

还要确保新ImageIcon()中的图像文件位置正确。