I'm trying to make my java app repaint each time the mouse has been moved to update the screen when the user moved over a diagram ( -> display the name of the diagram ) and when the user does not move over a diagram ( -> do not display any name of a diagram ). But this causes a huge lag when running the application ( I see the screen been repainted very slow, laggy, the screen is white empty for like a second each time before it's repainted; takes long to repaint ).
These are the the parts of the code which it's about:
public void mouseMoved(MouseEvent e) {
this.checkDiagramHovered(e.getX(),e.getY());
}
Which calls to a function that checks whether diagram was hovered and set variables whether a diagram was hovered and if so: which diagram was hovered (name to display, x and y position to do) and then repaint the app. So it basicly repaints the app each time a mousemovement was made to be sure it displays the name of a diagram ONLY when the user moved over it. But this causes the screen to lag a lot, choppy repainting.
Now I was wondering: what's the best way to solve this? S开发者_运维知识库hould I implement some kind of delay for checking the mousemovement or something if that can be done?
Thanks in advance,
Skyfe.
I'm assuming you're using Java Swing.
You have to take the checkDiagramedHovered
method out of the user interface thread, so the UI remains responsive.
public void mouseMoved(MouseEvent e) {
Thread thread = new Thread(new Runnable()
public void run() {
this.checkDiagramHovered(e.getX(),e.getY());
}
);
thread.start();
}
If checkDiagramedHovered
has any UI methods, you're have to run them in the UI thread.
SwingUtilities.invokeLater(new Runnable()
public void run() {
(UI method call)
}
);
Well, I would use Swing, not AWT. Swing is an extension to AWT that everybody uses these days. Then you can use a Tool Tip. You would need to override the getToolTipText(...) method for your component that displays the image.
in swing and awt, all events (mouse, keyboard) and painting are happening in the same thread. when you are calling repaint you submit a new job to that thread, that will actually call paint eventually. if the paint function takes too long, that thread (AWT Event queue thread) gets too busy to process mouse events and you see lag. the problem of the flickering you described also suggest slow paint function.
there are several things you can do: 1. use double buffering. this will solve the flicker but not the lag. 2. do the actual rendering in a different thread, and have the awt thread draw an offscreen image prepared by that thread. this will solve both problems.
in short, double buffering means you create an offscreen image and paint to it, and then paint the whole image at once using Graphics.drawImage()
精彩评论