Java Graphics.drawString并不总是有效

时间:2012-03-28 04:22:59

标签: java graphics drawstring

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

}

2 个答案:

答案 0 :(得分:0)

我认为您可能需要致电frame.repaint();,以便让您所绘制的内容正确显示,但我并不完全确定。我只记得在使用Java GUI时这是我自己的一些问题的原因。

答案 1 :(得分:0)

需要在SWING线程中运行代码!