paintcomponent repeats itself without any user interaction - java

I'm working on a project which uses paintcomponent.
The problem is that this paintcomponent method is executing itself repeatively without asking.I discovered this problem by creating a counter that raises the method runs everytime and I printed this out. Now is see that the method repeats itself randomly.
The problem is that this makes message boxes etc execute multiple times and freeze.
How can I solve this?

paintComponent is a low-level method which can be called at any time at the discretion of the GUI engine. It is not a place to instantiate any message boxes or similar, but to use low-level 2D graphics calls to paint your custom component. Your use case may actually call for a different mechanism whereby to refresh your screen.

Related

Is it possible to execute onDraw() right after invalidate(Rect)?

I added a breakpoint in my onDraw() method and noticed that my debugger only gets there after the method in which invalidate(rect) is, ends. Is it possible to be called right after?
Because I need to call invalidate(rect) twice in my method.
Thanks in advance.
No. Calling invalidate() is a signal to the framework that a portion of the screen is dirty and needs to be redrawn. The actual drawing doesn't happen immediately... it happens the next time through the main thread's event queue.
I have faced such problem with me and as alex saying it'll not happen. I can suggest one workaround that u can have your own implementation of onDraw() method with different name like myOnDraw() only when it should be not very heavy. so instead calling or depending upon onDraw() to be called immediately u can call that method which will work for u when u need it.

Java, applet: How to block the activation of paint() before init() finishes it's work

I found out that the method paint() gets called some time (it can't happen immediately, can it?) after the activation of init(), not after it finishes. I have a few objects that get created in init() and drawn in the paint() method. But the drawing starts before the objects get initialized. This causes exceptions, that are handled automatically. But it also causes the objects not to get drawn after the the first activation of paint()- they need to be redrawn in order to show up.
I was able to block the paint() method's work with an infinite cycle, placed int the beginning of the method, that doesn't stop until init() finishes it's work (I guess init() and paint() run in separate threads). But an employed Java programmer told me that this isn't an elegant solution- I should try to do something different (the guy didn't tell me what to do, he is not working with applets and I guess, he has never encountered this problem, that's why I'm asking here).
How can I make sure that the paint() method doesn't activate before init() finishes working, and how can I make it in an elegant way (what ever that's supposed to mean in this case...)?
EDIT:
I am using Dr. Java- for some reason, it runs the applet differently on two different computers: a really old laptop (7-years-old) that runs with Win XP and a 2-years-old desktop PC that runs with Win 7. I have made the mistake not to test with a browser...
The problem doesn't occur when testing with Dr. Java on the desktop. And the problem doesn't occur when running the applet on a browser. It only occurs with the editor installed on the laptop. I guess the problem is in the code editor running on the "old tech", not in the code.
The short answer is you can't. Init and paint are being called, as you suspected, by two different threads.
The most elegant solutions I think off of is
Check for nulls in the paint method
Use EventQueue.invokeLater in the init method and place the initialisation code within it, calling repaint when you're done
public void init() {
// do my initing...
inited = true;
repaint();
}
public void paint(Graphics g) {
if (!inited) {
return;
}
// do my painting...
}

multithreading for java graphics

I have a java application that streams raw data and draws real time plots accordingly. this is handled by calling methods from a class i wrote that uses the Graphics object. i implemented algorithms in an overridden paintComponent method to generate all the plots from the most recent data. i have other methods in my class to update variables used in the paintComponent method to draw the graphs.
in my main class, i update my graphs periodically in a timer event handler. in the event handler i call methods from my graphs class that update certain variables, do a few calculations, and then call repaint() (which apparently is the correct way to call the paintComponent method).
my problem is, the algorithms i use in the paintComponent method can take a (relatively) long time to complete depending on the amount and resolution of my plots. (i haven't exactly run into this problem yet, but i'm trying to address it now). of course i wouldn't want all this graphing to hog all the processing time of my application, so i was wondering if it's possible to have "paintComponent" execute in a separate thread.
what would happen if i created a subclass in my main to run in a separate thread and simply called the graph methods i described? would that automatically make all of those methods (including paintComponent) execute in the new thread? or would i have to modify my graph class itself for this to work? ideally i would like to avoid modifying my graphs class because i have already designed it to work within the NetBeans GUI builder as a JPanel, and i'd like to avoid breaking that functionality.
There's a couple options.
One method is to use two BufferedImages, where you draw on one in separate thread, and paint from the other one, and switch as drawing completes (for what I assume is a snapshot every so often.)
A much better solution is to have a model of directly renderable data (as in the data it holds can be drawn without performing any further algorithmic work on it).
This means you will perform your alogirthms on a separate thread, calculate the values that will be used to paint, call SwingUtilities.invokeLater to update the model. The model will then only get updated on the Swing thread, and when you repaint, you have access to exactly the data you need to draw (and no extraneous data).
If this data is still so much that painting takes a long time (ie: if you're drawing charts with tons of data points), you'll send to calculate which parts of your window need repainting and fire repaint() on just that. This piece should be a lat resort however. 99% of your performance will come from moving the algorithms into a separate thread, and giving the painter access to directly renderable data.
If you look at best practices on updating a TableModel with external data, what you have is the work that gets the data occurring in a background thread (typically SwingWorker) and then posted to the actual model via invokeLater() (This is so the data doesn't get modified while your paint() is trying to read it.) and then firing appropriate events from within the model update that tell the table what cells changed. The table then knows what part of its viewport needs repainting and fires the appropriate repaint() method. During this time the background thread can continue retrieving data and adding new updates to the event queue via invokeLater.
you have to redirect paint methods to the SwingWorker or Runnable#Thread (all output to the GUI must be wrapped into invokeLater), example here or here
Well, if you want to improve the responsiveness of the GUI you could do the lengthy work in a SwingWorker, although I don't know that doing so will speed up your application any more.
I have a java application that streams raw data and draws real time
plots accordingly. this is handled by calling methods from a class i
wrote that uses the Graphics object.
To complete other's answer:
you should really consider to use JFreeChart. It's a good library for drawing charts and you can modify dynamically the displayed dataset (and do a lot of more things).

JDialog fails to pack(), only sometimes

I have written a nifty thing in Java with a GUI that includes a JDialog that starts out rather small and then uses pack() to accommodate things the progam later puts in it. All of this is going on before the JDialog renders.
Then, to my surprise, about 80% of the time, when I run it, the window fails to resize. It seems to be entirely random, as it's theoretically doing exactly the same thing every time. Why on Earth would it do something different with the same code on the same machine five seconds later?
This problem, by the way, popped up when I enabled the native Windows look-and-feel for this GUI.
In my experience, when the GUI does random funny stuff like this, it might be a symptom of not doing all your GUI calls on the Event Dispatch Thread.
Make sure all your GUI calls from non-GUI threads are wrapped in SwingUtilities.invokeLater or invokeAndWait.
A quick google search turned up what seems to be a nifty way to check that your application conforms to the EDT-rules: http://thejavacodemonkey.blogspot.com/2007/08/using-aspectj-to-detect-violations-of.html

Design question about Swing GUI updates via PropertyChangeSupport

In the past I have used PCS to update Swing elements that displayed certain fields and everything worked as expected. However, I am now facing a relatively complex (in other words, terribly designed) UI that displays a lot of fields. Data updates come in bunches (a network packet containing new values for about 1,000 fields), and I was wondering what the proper way to handle something like this is.
My main concern is that whenever a data packet comes, 1,000 PropertyChangeEvents are triggered, causing 1,000 .repaint()'s (or .revalidate()'s or whatever). The more prudent way seemed to do something like "gui.stopRepainting(); fireAllThePropertyEvents(); gui.restartPainting();". Is there a way to do that, or is there maybe a better way to handle this ?
A repaint request is passed to the RepaintManager which in turn combines multiple requests into a single repaint.
I find it strange that you have 1000, fields of a single form. Assuming this in fact true then I doubt all 1000 will be visible at the same time. I believe the RepaintManager will only paint those that are visible so the overhead may not be as bad as you think.
I don't know of any way to stop the repaint, but maybe you could make the pane invisble, do the updates and then make it visible again.
Or maybe you can create a custom RepaintManager the does nothing. You instal it, do your updates and then reinstal the default manager.

Categories