为什么run函数没有调用paintComponenet()方法?

问题描述 投票:0回答:1

我正在使用 Java 编写 2d 游戏。我创建了 2 个类:主类和游戏面板类。

paintComponenet()
方法未按预期调用。下面是代码。

package main;

import javax.swing.JFrame;

public class Main {

    public static void main(String[] args) {

        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);
        window.setTitle("2D Adventure");

        GamePanel gamePanel = new GamePanel();

        window.add(gamePanel);
        window.pack();

        window.setLocationRelativeTo(null);
        window.setVisible(true);

        gamePanel.startGameThread();

    }
}


package main;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import javax.swing.JPanel;

public class GamePanel extends JPanel implements Runnable {

    //SCREEN SETTINGS
    final int originalTileSize = 16; //16x16 Tile
    final int scale = 3;

    final int tileSize = originalTileSize * scale; //48x48 Tile
    final int maxScreenCol = 16;
    final int maxScreenRow = 12;
    final int screenWidth = tileSize * maxScreenCol; //768 pixels
    final int screenHeight = tileSize * maxScreenRow; //576 pixels

    Thread gameThread;

    public GamePanel() {
        this.setPreferredSize(new Dimension(screenWidth, screenHeight));
        this.setBackground(Color.black);
        this.setDoubleBuffered(true);
    }

    public void startGameThread() {
        gameThread = new Thread(this);
        gameThread.start();
    }

    @Override
    public void run() {
        while (gameThread != null) {
            System.out.println("The game thread is running");
//            1. UPDATE: update character information
            update();
//            2. DRAW: draw the character at fps
            repaint();
        }
    }

    public void update() {
        System.out.println("Update method called");
    }

    public void paintComponenet(Graphics2D g) {
        System.out.println("paintComponent method called");
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.white);
        g2.fillRect(100, 100, tileSize, tileSize);

        g2.dispose();
    }

}

当线程运行时,我得到, 游戏线程正在运行 调用更新方法。

线程和窗口截图

我期待一个黑色背景的窗口和 100、100 处的白色方块。

java jframe overriding paintcomponent 2d-games
1个回答
0
投票

当覆盖它时,你拼错了它。 应该是

paintComponent(Graphics g)
它还需要一个
Graphics
实例。

  @Override
  public void paintComponent(Graphics g) {
        System.out.println("paintComponent method called");
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.white);
        g2.fillRect(100, 100, tileSize, tileSize);

        g2.dispose();
    }

为了确保重写正确的方法,请像我上面那样使用 @Override 注释。

© www.soinside.com 2019 - 2024. All rights reserved.