一般来说,我看不到任何关于代码的愚蠢之处,但我会说,您的组件层次结构似乎有点愚蠢。
你为什么不把你的物品分开呢?为了保持代码的可维护性和可测试性,我建议您提取
GameBoard
逻辑到另一个类。这将使您能够简化
GameMap
通过移除
paintComponent(...)
public class GameMap extends JPanel{
private JEditorPane status;
private GameBoard board;
public GameMap() {
status= createStatusTextPane();
board = new GameBoard();
this.setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));
this.add(board);
this.add(status);
}
//...all of the other stuff in the class
// note that you don't have to do anything special for painting in this class
}
然后你的
游戏板
可能看起来像
public class GameBoard extends JPanel {
//...all of the other stuff in the class
public void paintComponent(Graphics g) {
for (int row = 0; row < numrows; row++)
for (int column = 0; column < numcolumns ; column ++)
paintCell(g, row, column);
}
}