gpt4 book ai didi

Java Graphics.drawString 并不总是有效

转载 作者:行者123 更新时间:2023-12-01 05:24:16 26 4
gpt4 key购买 nike

以前有人遇到过这个问题吗?有时会显示字符串,有时会显示一半,有时则不显示。当使用 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);
}

}

最佳答案

我认为您可能需要调用frame.repaint();才能使您绘制的内容正确显示,尽管我不完全确定。我只记得这是我在使用 Java GUI 时出现一些问题的原因。

关于Java Graphics.drawString 并不总是有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9901117/

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