Search code examples
javagraphicsdrawstring

Java Graphics.drawString doesn't always work


Has anyone ever run into this issue before? Sometimes the string displays, sometimes half of it, sometimes none of it. The issue is worsened when using VolatileImage instead of BufferedImage as a backbuffer.

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();
    }
}

}

class GameCanvas extends 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);
}

}


Solution

  • The code needed to be ran in the SWING thread!