Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java hangman game repaint() not working

I have been making a hangman game to teach myself Java. I've got in the main body of the frame.

this.add(new PaintSurface(), BorderLayout.CENTER);

I've got:

private class PaintSurface extends JComponent {
    Shape found = null;

    public PaintSurface(){
        JOptionPane.showMessageDialog(null, "Repainting");
        Shape s;
        msgbox("LL: " + intLivesLost);
        switch(intLivesLost){
        //draw the Hanged man
        case 10:
            //Face + KILL
        case 9:
            //2nd Arm
        case 8:
            //1st Arm
        case 7:
            //2nd Leg
        case 6:
            //1st Leg
        case 5:
            //Body
        case 4:
            //Head
            shapes.add(s);
        case 3:
            //Horizontal Bar
            s = new Line2D.Float(100, 450, 250, 450);
            shapes.add(s);
            //Rope
            s = new Line2D.Float(250, 450, 250, 500);
            shapes.add(s);
        case 2:
            //Vertical Bar
            s = new Line2D.Float(100, 450, 100, 670);
            shapes.add(s);
        case 1:
            //Stand
            s = new Line2D.Float(40, 670, 460, 670);
            shapes.add(s);
            break;
        default:
            break;          
        }
    }

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setStroke(new BasicStroke(4));
        g2.setColor(Color.BLACK);

        for (Shape count : shapes){
            g2.draw(count);
        }
    }
}

And I'm using:

repaint();

...throughout the project each time the frame is updated, new letter guessed, incorrect guess, new game.

When the application first runs JOptionPane.showMessageDialog(null, "Repainting"); pops up, so I know it's been called then. Following that, the "Repainting" pop up doesn't appear any more, so I know that the repaint(); calls are doing nothing. I know the code is getting to the repaint(); calls, as I put a JOptionPane.showMessageDialog before and after them.

I've tried with no luck:

removeAll();
revalidate();
getContentPane().repaint();

Any hints and tips for this would be much appreciated.

Edit: I've tried it as you recommend, putting the code in "paint", think this is how I had it before, and it's still not working. Thanks though.

like image 594
Geoff Avatar asked Nov 08 '22 15:11

Geoff


1 Answers

  1. Do not override paint, override paintComponent or update instead according to your needs.
  2. Seems like you have a confusion between the paint, repaint and update methods. Read this: https://www.guiguan.net/repaint-paint-and-update/ if you are doing a game, repaint() will cause the repaint of the entire component, so you will have some performance issues.
like image 193
bns Avatar answered Nov 14 '22 22:11

bns