Java Chessboard件不能正确显示

时间:2016-03-29 06:59:05

标签: java image chess

我正在为一个班级制作一个国际象棋游戏,棋子没有正确显示。

这是我的代码:

package SucksLego;

import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

import SucksLego.CheesBoard.CaseEchiquier;
import lejos.nxt.ColorSensor.Color;

public class ChessBoard2 extends JFrame{

    private Container contents;

    private JButton [][] squares = new JButton [8][8];

    private int row = 7;
    private int col = 1;

    private ImageIcon piece = new ImageIcon ("chess-pawn-f.png");

    public ChessBoard2 (){

        super("Board");

        contents = getContentPane();
        contents.setLayout(new GridLayout (8,8));

        ButtonHandler buttonHandler = new ButtonHandler();

        for (int i = 0; i < 8; i++) {
            for (int j = 0; j < 8; j++) {

                squares[i][j] = new JButton();


                if((i+j) % 2 != 0){
                    squares[i][j].setBackground(getBackground().BLACK);
                }

                contents.add(squares [i][j]);
                squares[i][j].addActionListener(buttonHandler);

            }
        }

        squares [row][col].setIcon (piece);

        setSize(500,500);
        setResizable(false);
        setLocationRelativeTo(null);
        setVisible(true);

    }

    private boolean isValidMove(int i, int j){

        System.out.println("I: " + i + " J: " + j);
        return true;

    }   

    private void processClick (int i, int j){

        if(isValidMove(i,j) == false){
            return;
        }

        squares[row][col].setIcon(null);
        squares[i][j].setIcon(piece);
        row=i;
        col=j;

    }

    private class ButtonHandler implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {

            Object source = e.getSource();

            for (int i = 0; i < 8; i++) {
                for (int j = 0; j < 8; j++) {

                    if(source == squares[i][j]){
                        processClick(i,j);
                        return;
                    }

                }
            }

        }

    }

    public static void main(String[] args) {
        ChessBoard2 chess = new ChessBoard2();
    }

}

图标的尺寸为60 x 60。

图标显示为一个非常小的条款:

chess board

1 个答案:

答案 0 :(得分:1)

您无法获取图片,更改代码并将以下代码添加到ChessBoard2()

下的super("Board");构造函数中
 try{
    URL resource = ChessBoard2.class.getClassLoader().getResource("chess-pawn-f.png");
    img = ImageIO.read(resource);
    piece = new ImageIcon(img);
 }
 catch (IOException e)
 {
    e.printStackTrace();
 }