Jframe Paint method does not show the drawings on the screen

Asked

Viewed 439 times

3

I overloaded the method paint and I’m using the Graphics2d class to try to make the drawings, but nothing is being drawn on the screen, I could see with the Debugger that the method is run constantly but the drawings do not appear on the screen, this is the method:

@Override
public void paint(Graphics g) { 
    super.paint(g);

    Graphics2D g2d = (Graphics2D)g.create();

    g2d.setColor(Color.yellow);
    g2d.drawLine(0, 0, WIDTH, HEIGHT);

    g2d.dispose();
}

The main class implements the interface Runnable, firing a thread and within the method run I call the method repaint() jframe:

public void run(){
     repaint();
     try {
        Thread.sleep(100);
     } catch (InterruptedException ex) {
        Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
     }

Here is the method main where the thread is fired:

public static void main(String[] args) {
    Game game = new Game();
    game.createGameWindow("Game");
    new Thread(game, "Game").start();
}

I’ve looked for several tutorials behind a solution, on Youtube, tutorial sites etc, all do exactly what I’m doing but none worked, what might be the problem?

1 answer

3

The problem is that you are creating a new object by doing:

Graphics2d g2d = (Graphics2d)g.create();

That is why your drawing does not appear on the screen (it is occurring in this other Graphics2D that you created).

You must simply convert g in an object Graphics2D, via a type cast:

Graphics2D g2d = (Graphics2D)g;

According to that other answer, that type cast is always valid from Java 1.2.

Remembering that by doing this type cast, should be removed the g2d.dispose(); of the end.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.