有没有人遇到过这个问题?有时字符串显示,有时显示一半,有时不显示。当使用 VolatileImage 而不是 BufferedImage 作为后台缓冲区时,问题会更加严重。
public class Game3D {
public static void main(String[] args) {
Game3D game = new Game3D();
game.start();
}
public Game3D() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canv = new GameCanvas();
canv.setPreferredSize(new Dimension(800, 600));
frame.add(canv);
frame.pack();
frame.setVisible(true);
}
private JFrame frame;
private GameCanvas canv;
public void start() {
canv.createBuffer(canv.getPreferredSize());
loadingScreen("Loading", 10);
}
public void loadingScreen(String msg, int done) {
Graphics2D g = canv.img.createGraphics();
try {
g.setColor(Color.BLACK);
g.fillRect(0, 0, canv.getWidth(), canv.getHeight());
int sizeX = 400, sizeY = 50;
int loadX = canv.getWidth() / 2 - sizeX / 2;
int loadY = canv.getHeight() / 2 - sizeY / 2;
g.setColor(Color.RED);
g.drawRect(loadX, loadY, sizeX, sizeY);
g.fillRect(loadX + 2, loadY + 2, (int) (sizeX / 100F * done), sizeY - 3);
int textX = canv.getWidth() / 2 - g.getFontMetrics().stringWidth(msg) / 2;
int textY = canv.getHeight() / 2 - g.getFontMetrics().getHeight() / 2;
g.setColor(Color.WHITE);
g.setFont(canv.font);
g.drawString(msg, textX, textY);
} finally {
g.dispose();
}
}
}
类 GameCanvas 扩展 Canvas {
GameCanvas() {
}
BufferedImage img;
Font font;
void createBuffer(Dimension dim) {
img = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
font = new Font(Font.MONOSPACED, Font.PLAIN, 16);
}
@Override
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}