【发布时间】:2011-01-12 21:30:18
【问题描述】:
我不知道为什么它不会显示。首先,我创建组件的一个实例,然后将其添加到二维 JPanel 数组中的某个元素。然后我遍历该数组并将每个 JPanel 添加到另一个 JPanel 容器中,该容器将容纳所有 JPanel。
然后我将最后一个容器添加到我的 JFrame 窗口并将可见性设置为 true,它应该是可见的吗?
public class View extends JFrame {
Board gameBoard;
JFrame gameWindow = new JFrame("Chess");
JPanel gamePanel = new JPanel();
JPanel[][] squarePanel = new JPanel[8][8];
JMenuBar gameMenu = new JMenuBar();
JButton restartGame = new JButton("Restart");
JButton pauseGame = new JButton("Pause");
JButton log = new JButton("Log");
View(Board board){
gameWindow.setDefaultCloseOperation(EXIT_ON_CLOSE);
gameWindow.setSize(400, 420);
gameWindow.getContentPane().add(gamePanel, BorderLayout.CENTER);
gameWindow.getContentPane().add(gameMenu, BorderLayout.NORTH);
gameMenu.add(restartGame);
gameMenu.add(pauseGame);
gameMenu.add(log);
gameBoard = board;
drawBoard(gameBoard);
gameWindow.setResizable(false);
gameWindow.setVisible(true);
}
public void drawBoard(Board board){
for(int row = 0; row < 8; row++){
for(int col = 0; col < 8; col++){
Box box = new Box(board.getSquare(col, row).getColour(), col, row);
squarePanel[col][row] = new JPanel();
squarePanel[col][row].add(box);
}
}
for(JPanel[] col : squarePanel){
for(JPanel square : col){
gamePanel.add(square);
}
}
}
}
@SuppressWarnings("serial")
class Box extends JComponent{
Color boxColour;
int col, row;
public Box(Color boxColour, int col, int row){
this.boxColour = boxColour;
this.col = col;
this.row = row;
repaint();
}
protected void paintComponent(Graphics drawBox){
drawBox.setColor(boxColour);
drawBox.drawRect(50*col, 50*row, 50, 50);
drawBox.fillRect(50*col, 50*row, 50, 50);
}
}
还有最后一个问题。注意每个 Box 组件是如何有一个位置的,当我将组件添加到 JPanel 并将 JPanel 添加到我的 JFrame 时,位置会发生什么变化? 它相对于其他 Box 组件的位置是否仍然相同?
【问题讨论】:
-
你的
main在哪里?据我所知,View的构造函数从未被调用过。此外,View类是JFrame,它永远不会可见。 -
对了,忘记说了。构造函数在另一个类 Game 中调用,其中“board”作为参数传递。 Board 拥有一个 Square[][] 和 getSquare 方法获取索引 col, row 处的正方形。 getColour 方法从正方形中获取 squareColour 属性。板子通过遍历数组在构造函数中设置 squareColour。
-
gameWindow 是否可见?另外,奇怪的是我的菜单是可见的,按钮也是可见的。只是盒子不是。