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.
精彩评论