Java Swing窗口网格与图形无法显示问题求助
解决Java Swing网格与苹果图形不显示问题
问题根源
- paintComponent未调用自定义绘制方法:
paintComponent是Swing组件的核心绘制入口,当前仅调用super.paintComponent(g)完成背景绘制,未调用自定义的draw(g)方法,导致网格和苹果图形从未被执行绘制。 - newApple方法变量赋值错误:两次对
appleX赋值,appleY始终为默认初始值0,未按网格单元计算位置。 - Timer未触发重绘:Timer启动后,
actionPerformed方法为空,未调用repaint()触发组件重绘,无法更新画面。 - 网格线条颜色与背景冲突:绘制网格时未设置线条颜色,默认黑色与背景色一致,导致网格不可见。
修正后的代码
GamePanel类修改版
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.Random; public class GamePanel extends JPanel implements ActionListener { static final int SCREEN_WIDTH = 600; static final int SCREEN_HEIGHT = 600; static final int UNIT_SIZE = 25; static final int GAME_UNITS = (SCREEN_WIDTH * SCREEN_HEIGHT) / UNIT_SIZE; static final int DELAY = 75; final int x[] = new int[GAME_UNITS]; final int y[] = new int[GAME_UNITS]; int bodyParts = 6; int applesEaten; int appleX; int appleY; char direction = 'R'; boolean running = false; Timer timer; Random random; GamePanel() { random = new Random(); this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT)); this.setBackground(Color.black); this.setFocusable(true); this.addKeyListener(new MyKeyAdapter()); startGame(); } public void startGame() { newApple(); running = true; timer = new Timer(DELAY,this); timer.start(); } // 在paintComponent中调用draw方法,触发自定义绘制 public void paintComponent(Graphics g) { super.paintComponent(g); draw(g); } public void draw(Graphics g) { // 设置网格线条为白色,与黑色背景区分 g.setColor(Color.white); for (int i = 0; i <= SCREEN_HEIGHT / UNIT_SIZE; i++) { g.drawLine(i * UNIT_SIZE, 0, i * UNIT_SIZE, SCREEN_HEIGHT); g.drawLine(0, i * UNIT_SIZE, SCREEN_WIDTH, i * UNIT_SIZE); } // 绘制红色苹果 g.setColor(Color.red); g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE); } // 正确给appleX和appleY赋值,生成网格内的随机位置 public void newApple() { appleX = random.nextInt((int)(SCREEN_WIDTH / UNIT_SIZE)) * UNIT_SIZE; appleY = random.nextInt((int)(SCREEN_HEIGHT / UNIT_SIZE)) * UNIT_SIZE; } public void move() { } public void checkApple() { } public void checkCollisions() { } public void gameOver(Graphics g) { } // Timer触发时重绘组件,同时预留游戏逻辑扩展入口 @Override public void actionPerformed(ActionEvent e) { if(running){ move(); checkApple(); checkCollisions(); } repaint(); } public class MyKeyAdapter extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { } } }
关键修改说明
- paintComponent方法:添加
draw(g)调用,确保自定义绘制逻辑被执行。 - newApple方法:将第二次赋值改为
appleY,保证苹果在网格内随机位置生成。 - actionPerformed方法:添加
repaint()调用,让Timer定期触发画面更新;同时保留后续游戏逻辑的扩展入口。 - draw方法:绘制网格前设置
g.setColor(Color.white),让网格在黑色背景上可见。
内容的提问来源于stack exchange,提问作者Evan Schulte
相关产品推荐
相关产品推荐

