我正在做一個項目的國際象棋遊戲,我想要做的第一件事之一是創建一個框架,然後用64個JButtons (有組織的8x8),每個將作爲國際象棋棋盤上的廣場。我對Java仍然很陌生,但我仍然認爲我不應該得到我收到的錯誤,這是前一段時間沒有發生的事情,但是當幀被加載之前,沒有JButton沒有。試圖創建一個完整的JButtons框架,但我的JButtons不會加載
在使用3D數組向我的JButton添加座標時,我似乎遇到了一個問題,我不斷收到錯誤「方法添加(ChessSquare)未定義類型ChessBoard」,在Eclipse之上不斷爲我提供幫助,但我認爲我可能會通過接受他們而使事情變得更糟。
另一個問題是,當我嘗試從ChessSquare的3D數組中保存方塊的座標時。
我目前有2個班級,ChessBoard和ChessSquare,我試圖讓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));
}
}
嗨,謝謝你的回答,pack()是一個非常好的接觸。 我仍然無法使用add()方法: 'ChessSquare chessSquare = new ChessSquare(i,l); square = new int [i] [l]; frame.add(chessSquare);' 如果我使用ChessSquare,它將不起作用,但是當我使用chessSquare時,框架將加載,但不會出現任何按鈕。我確信我正在解決這個問題,但我無法弄清楚什麼是錯的。 – JmJ 2013-03-22 05:48:32