我正在尝试使用枚举来存储一堆字符串,但是当我将它们转换为字符串时它不起作用。我收到错误消息“无法从 String 转换为 ChessSquare.SelectedPiece。我认为这只会有一点改变,但我找不到要改变的地方。
这是我的代码:
package Logic;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
//chess square class, 1 instance of which for each square in the grid
@SuppressWarnings("serial")
public class ChessSquare extends JButton {
//instance variables for position and pieces
public int posX;
public int posY;
public String currentPiece;
public enum selectedPiece{
NONE, PAWN, ROOK, KNIGHT, BISHOP, QUEEN, KING
}
selectedPiece piece;
//load images and cast into icons
BufferedImage buttonIcon = ImageIO.read(new File(piece));
ImageIcon Icon = new ImageIcon(buttonIcon);
BufferedImage
//constructor for chess squares
public ChessSquare(int x, int y, double p) throws IOException {
this.setIcon(Icon);
setVisible(true);
}
//accessor method for position
public void squarePos(int x, int y){
this.posX = x;
this.posY = y;
}
//accessor method for currentPiece
public void cPiece(){
this.currentPiece = piece;
}
//specify what each value of enum slectedPiece represents
public void selectedPiece(){
switch (piece){
case NONE:
piece = "E:\\Eclipse\\ChessF\\src\\Images\\EmptySquare.jpg";
case PAWN:
piece = "E:\\Eclipse\\ChessF\\src\\Images\\Pawn.jpg";
case ROOK:
piece = "E:\\Eclipse\\ChessF\\src\\Images\\Rook.jpg";
case KNIGHT:
piece = "E:\\Eclipse\\ChessF\\src\\Images\\Knight.jpg";
case BISHOP:
piece = "E:\\Eclipse\\ChessF\\src\\Images\\Bishop.jpg";
case QUEEN:
piece = "E:\\Eclipse\\ChessF\\src\\Images\\Queen.jpg";
case KING:
piece = "E:\\Eclipse\\ChessF\\src\\Images\\King.jpg";
}
}
}