gpt4 book ai didi

Java 图形不起作用?

转载 作者:行者123 更新时间:2023-12-01 11:04:23 26 4
gpt4 key购买 nike

我正在尝试使用 YouTube 教程制作游戏,目前正在尝试创建并填充窗口大小的矩形。它不会变黑,而是保持灰色(我的默认颜色)。

有什么想法吗?提前致谢!

代码:

import javax.swing.*;
import java.awt.image.BufferStrategy;
import java.awt.*;

public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;

public static int width = 300;
public static int height = width / 16 * 9;
public static int scale = 3;

private Thread thread;
private JFrame frame; // Creates a window
private boolean running = false; // Checks to see if the game is running

public Game() {
Dimension size = new Dimension(width * scale, height * scale); // The window size
setPreferredSize(size); // Choosing the size I want

frame = new JFrame(); // Calling the frame
}

public synchronized void start() {
running = true;
thread = new Thread(new Game(), "Display"); // Calling the class
thread.start(); // Starting the class
}

public synchronized void stop() { // Ending the game
running = false;
try {
thread.join();
} catch(InterruptedException e) {
e.printStackTrace();
}
}

public void run() {
while(running) {
update();
render();
}
}

public void update() {

}

public void render() {
BufferStrategy bs = getBufferStrategy();
if(bs == null) {
createBufferStrategy(3); // Triple buffering strategy (speeds up process)
return;
}

Graphics g = bs.getDrawGraphics(); // Create a link between buffer and drawing on screen
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.dispose();
bs.show();
}

public static void main(String[] args) {
Game game = new Game(); // Calling the class to be able to change things in it
game.frame.setResizable(true); // Stopping window changing in size (causes graphical errors)
game.frame.setTitle("Game Window");
game.frame.add(game); // Fills the window with the class (can be done because of 'Canvas')
game.frame.pack(); // Sets the size of the window based on what is in the component above.
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null); // Centres the window in the screen
game.frame.setVisible(true);

game.start(); // Starts the game
}
}

最佳答案

更改 thread = new Thread(new Game(), "Display"); 以使用 this 而不是 new Game()

关于Java 图形不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33089081/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com