开发者

Java JFrame / Canvas doesn't repaint

开发者 https://www.devze.com 2023-04-09 10:29 出处:网络
A mouse listener calls repaint() and I can see that it does actually go past the drawing part because I see globalcounter incremented in the output of System.out.println(). On the screen, however, I d

A mouse listener calls repaint() and I can see that it does actually go past the drawing part because I see globalcounter incremented in the output of System.out.println(). On the screen, however, I don't see any change until I minimize the window and maximize again, resize it, or move it out of the visible screen area and back in. Obviously I'd like it to update without my intervention.

class GUI exten开发者_如何学运维ds javax.swing.JFrame {
int globalcounter=0;
  class MyCanvas extends Canvas {

  @Override
  public void paint(Graphics g) {
    globalcounter++;
    g.drawString(globalcounter,100,100);
    System.out.println(globalcounter);
    }

  }
}

(Originally I was loading an image from a file that got constantly updated (webcam) and painting it on the canvas. When I dragged it partly out of the visible screen area and back in, the part that has been 'outside' was refreshed, the rest not.)

revalidate() instead of repaint() didn't change anything.

I know this post is a duplicate to Java repaint not working correctly but when I posted it there it was deleted.


Why are you adding an AWT component, Canvas, to a Swing component, JFrame? You should stick with Swing components only. And also do you know the size of your MyCanvas, and how have you added it to the JFrame as you don't show this code.

Consider

  • using a JPanel instead of a Canvas object,
  • drawing in its paintComponent method,
  • showing us an sscce if you're still stuck.
  • And also, if all you're doing is drawing text, use a JLabel rather than drawing in paint/paintComponent, and change its text with its setText(...) method.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号