我是 Java 新手,整个使用数组 + 使用类及其方法来填充和显示数组。我花了过去 2-3 个小时,研究这个并检查谷歌的各种答案,但似乎没有任何帮助,我仍然被困住。在使用数组时,我真的不知道如何使用 rectangle1 类中的方法。
主类:
public static void main(String[] args) {
GameBoard frame = new GameBoard();
}
游戏板类
public class GameBoard extends JFrame {
public GameBoard() {
JFrame frame = new JFrame();
frame.setBounds(0, 0, 195, 215);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Rectangle1 board[][] = new Rectangle1[3][3];
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = new Rectangle1(0, 0, 195, 215);
if ((row + col) % 2 == 0) {
Graphics g = null;
board[row][col].paint(g);
g.setColor(Color.yellow);
g.fillRect(0, 0, 195, 215);
} else {
Graphics h = null;
board[row][col].paint(h);
h.setColor(Color.red);
h.fillRect(0, 0, 195, 215);
}
frame.add(board[row][col]);
}
}
}
}
矩形 1 类。
public class Rectangle1 extends JComponent {
/** post: getX() == x and getY() == y
* and getWidth() == w and getHeight() == h
* and getBackground() == Color.black
*/
public Rectangle1(int x, int y, int w, int h) {
super();
setBounds(x, y, w, h);
setBackground(Color.black);
}
/** post: this method draws a filled Rectangle
* and the upper left corner is (getX(), getY())
* and the rectangle's dimensions are getWidth() and getHeight()
* and the rectangle's color is getBackground()
*/
public void paint(Graphics g) {
g.setColor( getBackground() );
g.fillRect(0, 0, getWidth()-1, getHeight()-1);
paintChildren(g);
}
}