java图形在绘制到屏幕时会滞后
我松散地跟随this persons code做一个乒乓球游戏
但是,当我运行程序时,屏幕将显示1。变成纯白色,2。变白,几秒钟后,或3秒钟后,在屏幕上画画。立即在屏幕上涂色
我目前没有太多的代码。为什么有时在画框时会出现延迟?我该怎么解决这个问题?有更好的方法吗
[主要课程]
import javax.swing.JFrame;
public class Main extends JFrame {
public static final int FRAME_WIDTH = 900, FRAME_HEIGHT = 500;
GamePanel game;
public Main() {
this.setTitle("Pong");
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
game = new GamePanel(this);
add(game);
}
public static void main(String[] args) {
Main main = new Main();
}
public int getWidth() {
return FRAME_WIDTH;
}
public int getHeight() {
return FRAME_HEIGHT;
}
}
[游戏面板]
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JPanel;
public class GamePanel extends JPanel {
private Main main;
private Player player;
private int playerScore = 0;
private int oppScore = 0;
private int yCenter;
public GamePanel(Main main) {
setBackground(Color.BLACK);
this.main = main;
this.yCenter = (main.getHeight() / 2) - 75;
player = new Player(main, 25, yCenter);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.setFont(new Font("Courier", Font.BOLD, 40));
g.drawString(playerScore + " - " + oppScore, (main.getWidth() / 2) - 75, 50);
player.draw(g);
}
}
[玩家等级]
import java.awt.Graphics;
public class Player {
private Main main;
private static final int PLAYER_WIDTH = 30, PLAYER_HEIGHT = 125;
private int x, y;
public Player(Main main, int x, int y) {
this.main = main;
this.x = x;
this.y = y;
}
public void draw(Graphics g) {
g.fillRect(x, y, PLAYER_WIDTH, PLAYER_HEIGHT);
}
}
共 (0) 个答案