私はプロジェクト用のチェス ゲームを作成しています。最初にやりたいことの 1 つは、フレームを作成し、それを 64 個の JButton (8x8 で構成) で埋めて、それぞれがチェス ボードの正方形として機能するようにすることです。私はまだJavaに非常に慣れていませんが、私が得ているエラーが発生するはずはないと思います.しばらく前には発生していませんでしたが、フレームが以前にロードされたときに、JButtonsのどれもやりました。
3D 配列を使用して JButton に座標を追加するときに問題が発生しているようです。「メソッド add(ChessSquare) は ChessBoard 型に対して定義されていません」というエラーが表示され続けます。しかし、それを受け入れることで事態をさらに悪化させているのではないかと思います。
もう 1 つの問題は、ChessSquare の 3D 配列から正方形の座標を保持しようとするときです。
現在、ChessBoard と ChessSquare の 2 つのクラスがあります。ChessBoard に ChessSquare を使用してピースを作成させようとしています。
よくわからなかったらすみません、信じられないほど疲れています。
助けてくれてありがとう。
これが私のコードです:
ボード:
import java.awt.GridLayout;
import java.io.IOException;
import javax.swing.JFrame;
import Logic.ChessSquare;
public class ChessBoard {
//chess board constructor
public ChessBoard() throws IOException {
//create grid and grid dimensions
GridLayout grid = new GridLayout(8,8);
//create frame and set specifications of frame
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(458, 458);
frame.setTitle("I'm starting to prefer C");
//initialise 3D array
ChessSquare[][] square = new ChessSquare[8][8];
//create 64 instances of ChessSquare and assign each square as an element in the 3D array
for (int i = 0; i < 8; i++){
for(int l = 0; l < 8; l++){
square[i][l] = new ChessSquare();
this.squarePos(square[i][l]); //this is where my main gripe is
}
}
}
public static void main(String[] args) throws IOException{
new ChessBoard();
}
}
四角:
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
public class ChessSquare extends JButton {
/**
*
*/
private static final long serialVersionUID = 1L;
//instance variables for position and piece
public int squarePos;
public String selectedPiece;
//accessor method for position
public void squarePos(){
int squarePos = ChessBoard.square;
}
//constructor for chess squares
public ChessSquare() throws IOException {
BufferedImage buttonIcon = ImageIO.read(new File("E:\\Eclipse\\ChessF\\src\\Images\\EmptySquare.jpg"));
JButton button = new JButton(new ImageIcon(buttonIcon));
}
}