Java workman repaint () not working

I am making a hangman game to teach myself Java. I hit the main part of the frame.

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

I have:

 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 use:

 repaint(); 

... throughout the project, every time the frame is updated, a new letter guesses, an incorrect assumption, a new game.

When the application first starts JOptionPane.showMessageDialog (null, "Repainting"); pops up, so I know what it's called then. After that, the Repainting popup does not appear anymore, so I know that repaint (); calls do nothing. I know the code goes to repaint (); calls when I add JOptionPane.showMessageDialog before and after them.

I tried with no luck:

RemoveAll ();
double-check ();
. GetContentPane () repaint ();

Any tips and tricks for this would be greatly appreciated.

Edit: I tried this, as you recommend, putting the code in the β€œpaint”, think it was like this before, and it still doesn't work. Thanks, though.

+6
source share
2 answers

I solved this by drawing a drawing on a separate panel, and everything works fine. Thanks for the help.

0
source
  • Do not redefine paint, redefine paintComponent or update according to your needs.
  • It looks like you have a confusion between drawing, repainting, and updating methods. Read this: https://www.guiguan.net/repaint-paint-and-update/ , if you are making a game, repaint () will cause the component to be redrawn, so you will have some performance issues.
+1
source

All Articles