我正在尝试重新绘制我在新游戏动作中创建的蛇游戏。它正在工作但它不能清除旧的蛇体或阻挡屏幕。
public class View extends JFrame implements ActionListener {
private static final long serialVersionUID = -2542001418764869760L;
public static int viewWidth = 20;
public static int viewHeight = 20;
private SidePanel side;
private JMenuBar menuBar;
private JMenuItem newGameButton;
private JMenu menu, mode;
private SnakeController sController;
private GamePanel gamePanel;
/*
* Initialize the game's panels and add them to the window.
*/
public View() {
menuBar = new JMenuBar();
menu = new JMenu("Menu");
menuBar.add(menu);
newGameButton = new JMenuItem("New Game");
menu.add(newGameButton);
newGameButton.addActionListener(this);
mode = new JMenu("Mode");
menuBar.add(mode);
this.setJMenuBar(menuBar);
this.gamePanel = new GamePanel(this);
this.side = new SidePanel(this);
this.add(gamePanel, BorderLayout.CENTER);
this.add(side, BorderLayout.EAST);
Tuple position = new Tuple(10, 10);
sController = new SnakeController(position, side, gamePanel);
this.addKeyListener((KeyListener) new Listener());
// this.requestFocus();
pack();
}
public static void main(String args[]) {
View window = new View();
window.setTitle("og-snake");
window.setSize(700, 400);
window.setVisible(true);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newGameButton) {
System.out.println("clicked");
gamePanel.removeAll();
gamePanel.revalidate();
gamePanel.repaint();
Tuple position = new Tuple(10, 10);
sController = new SnakeController(position, side, gamePanel);
sController.start();
}
}
这是我的主要课程,它基本上使视图添加了侧面板和棋盘面板。所执行的动作是在游戏面板上的新游戏动作上完成的。
public class GamePanel extends JPanel {
public static ArrayList<ArrayList<ColorCell>> snakeGrid;
public static int viewWidth = 20;
public static int viewHeight = 20;
ArrayList<ColorCell> data;
SnakeController sc ;
private View game;
public GamePanel(View game) {
this.game = game;
this.snakeGrid = new ArrayList<ArrayList<ColorCell>>();
this.data = new ArrayList<ColorCell>();
for (int i = 0; i < viewWidth; i++) {
data = new ArrayList<ColorCell>();
for (int j = 0; j < viewHeight; j++) {
ColorCell c = new ColorCell(2);
data.add(c);
}
snakeGrid.add(data);
}
setLayout(new GridLayout(viewWidth, viewHeight, 0, 0));
setPreferredSize(new Dimension(400,400));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < viewWidth; i++) {
for (int j = 0; j < viewHeight; j++) {
add(snakeGrid.get(i).get(j).viewCell);
}
}
}
}
答案 0 :(得分:2)
gamePanel.removeAll();
gamePanel.fillGrid();
gamePanel.revalidate();
gamePanel.repaint();
Tuple position = new Tuple(10, 10);
this.gamePanel = new GamePanel(this);
this.add(gamePanel,BorderLayout.CENTER);
该代码并没有真正做任何事情。将组件添加到BorderLayout的CENTER时,它不会替换原始组件。
Swing绘画的工作方式是首先绘制添加的最后一个组件。所以这意味着新添加的面板被绘制,然后原始面板被涂在新添加的面板的顶部。
因此,由于您有逻辑从原始gamePanel中删除所有组件,因此无需创建新的gamePanel。只需重置游戏面板的状态即可。