Jframe Paint Method Does Not Display Drawings on Screen

3

I have overloaded the paint method of Jframe and am using the Graphics2D class to try to draw the drawings, but nothing is being drawn on the screen, I could see with the debugger that the method runs 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 repaint() method of 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 main method 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 already looked for a lot of tutorials behind a solution, on YouTube, tutorial sites etc, they all do exactly what I'm doing but none worked, what could be the problem?     

asked by anonymous 18.05.2014 / 19:17

1 answer

3

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

  

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

So your drawing does not appear on the screen (it's occurring in that other Graphics2D you created).

You should simply convert g to a Graphics2D object, via type cast :

Graphics2D g2d = (Graphics2D)g;

According to this other answer , this type cast is always valid since Java 1.2.

Remembering that while doing this type cast , you should remove g2d.dispose(); from the end.

    
18.05.2014 / 19:39