I'm new in Java Swing and I have a strange problem to refresh my JPanel
.
I create a static JPanel
componant in my frame and I call a static method from a FileListenner
to repaint my JPanel
public static void repaintPlan(JPanel f) {
f.paint(f.getGraphics());
f.revalidate(); // or validate
}
I mean, when I detect change in file content, I calculate the new coordinates and I repaint the JPanel
(I create a class exends from JPanel to define
paintComponent()` method)
Everything is working fine when I run the app, and the repaint works when a change data in file; but if I click with my mouse in the Jpanel
, the repaint()
method doesn't work anymore. Can you tell me why after clicking on JPanel
, repainting doesn't work ?
Sorry for my bad english Thanks in advance:)
Edit: Thanks for your repsonses! But even if I use repaint()
method, it's the same problem. I'm trying to understand what happens when I click on JPanel
. Should I use mouse events in Swing to solve the problem?
I resolve my problem by overriding mouse event methods of my JPanel like this
thanks
1) for Swing
JComponents
is there methodpaintComponent()
, methodpaint()
is for Top-Level Containers (JFrame
, JDialog ...) and forAWT Components
2) don't use
getGraphics()
this method created snapshot that after callingvalidate
,revalidate
,repaint
expired3) you have look at tutorial about 2D Graphics, examples here
4) in the case that you'll have real question, please edit your question with SSCCE
You might get some insight from this example that responds to mouse pressed events. In this case,
paintComponent()
is called automatically when the color is updated. See also Painting in AWT and Swing.No, paintComponent is not called after a mouse press, not unless you've got some code that makes it do this. For example:
As you can plainly see, in a plain JPanel, paintComponent is not called after any mouse action unless you change the size of the GUI.
Something else is wrong with your GUI, and also, it shouldn't matter if paintComponent is called once or several times since your program logic should not depend on whether or not this method gets called.