In swing-java, where does the Graphics instance come from? - java

When an update request is delivered to swing (either system triggered e.g. because of a resize or a block by another window, or app-triggered e.g. by a call to repaint() method), how is this request actually handled? What procedure takes place in that RepaintManager thing?

From your comment:
Do you know what happens in peer.getGraphics()?
That depends on which peer implementation is used.
One implementation is WComponentPeer (used when running on Windows), which seems to use two ways for getting the Graphics object:
If the component has a parent of type Window (or is one itself) which in turn has a back buffer immage associated, that image's Graphics object is returned. This depends on the type of image but is most likeley a SunGraphics2D instance, created in createGraphics().
Otherwise a ScreenUpdateManager instance is retrieved and createGraphics(...) is called on it which in turn returns a new SunGraphics2D instance.
Please note that this is just one possible way and it highly depends on the OS, the JVM and UI toolkit used.

Related

paintcomponent repeats itself without any user interaction

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.

Android: OpenGL: glGenTextures not working in constructor?

Can anyone tell me why glGenTextures() isn't working in my constructor?
Here is how my project is setup:
A custom renderer is used which calls .draw on the current active stage.
When a stage is created it assigns itself (the end line of its constructor) to the static Global.activeStage.
Now the renderer calls .draw on the currently active stage which reference is kept inside Global.activeStage.
In the stage I have a function which loads all textures that are needed in the stage.
If I call this function the first time .draw is called there is no problem.
If I call it in the constructor though, everything works except glGenTextures() - it creates a zero value rather than 1..2..3 and so on.
In both cases a global GL10 reference is used rather than the one .draw gets, so it's not the problem.
It seems as if everything works ONLY if there is already a reference to the current stage I'm using (if the stage is created e.g. the constructor has already run).
I am not sure if it is related, but the stage is created in a Thread after onCreateSurface ends.
I could post some of the code if you say which parts would be relevant.
I am quite sure you have to run all openGL operations on the Thread associated with openGL. This is why it works when called from your draw() method called from the renderer (which runs on the GL-Thread) but not from the constructor (which runs on another Thread as you say).

Accessing modal dialog variable after calling dispose method

Situation: a main form calls a modal jDialog with textboxes in which parameters are filled in by the user to create or modify an instance of a certain class, call it ClassA.
When the dialog needs to modify an existing instance, it is passed in the constructor as a parameter. Otherwise the jDialog will create a new instance of ClassA.
Problem: the mainform needs to access that new instance, and I think it is unclean code to pass the entire main form as a parameter, and let the dialog push the new instance into it by a method call, because that way a perfectly re-usable stand-alone dialog becomes only usable with one single main form that needs a certain classname and method to receive the new instance.
It is much more logical to make the main form get the new instance from the jdialog after the OK button is clicked, by calling a getClassAInstance() method (which could be called also when an existing instance was being modified). The method is called after the "setVisible(true)" method on a new instance of the jdialog in question. The dialog appears, the thread of the main form will sleep until the dialog is closed (because it is modal). The OK button calls the dispose() method of the jDialog, then the very next statement is the getClassAInstance() call on the jDialog by the mainform.
Here's the same thing in code..
ClassAInstanceMakerDialog imd = new ClassAInstanceMakerDialog(this, true);
imd.setVisible(true);
//imd.dispose(); after OK button click
System.out.println(imd.getClassAInstance()); //return a new ClassA instance
//output: whatever ClassA.toString() should return, works fine
Question: I've tried it and it seems to work perfectly fine. But, is it a good code? Is there any danger of the getClassAInstance() method returning "null", because the garbage collector collected the ClassA instance after the jDialog was disposed and before the main form could complete the call?
Please excuse me if I didn't make myself clear, I'm not a native English speaker. If you would rather see some code, let me know...
I think it's perfectly legal to access the member variable of your dialog instance that holds the ClassA instance, the dialog instance will not be garbage collected until it goes out of scope, not just because you called dispose on it.
I'd give slight preference to a solution where you define an event handler interface with a signature of
someThingHappened(ClassA toThisObject), make your mainform or anything that might be interested that ClassA thing implement that interface make it possible to add listeners to the dialog before making it visible.
That way, you would loosen the coupling between the dialog and the main form a little.
I don't think that dispose() sets the JDialog up for garbage collection, but instead just releases resources. The dialog is still re-usable as per the Window API (since JDialog inherits this method from Window):
Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable.
The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).
Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for more information.
As long as there are valid reachable references to the JDialog object still present, it will not be garbage collected. I think that the cost of disposing the dialog is that your code will need to spend a (very) little bit of time to re-create the resources.
It is perfectly reasonable and appropriate to have an IDisposable include properties or methods which may be used after Dispose is called to return information about things which happened before Dispose was called. Rather than blindly enforcing a rule that any and all methods of a disposed object should throw an ObjectDisposedException, one should instead consider which methods and properties do or do not make sense on disposed objects. Attempting to access a disposed object should throw ObjectDisposedException in preference to re-acquiring released resources or letting escape some other exception which occurs as a consequence of the disposal. If the method or property access can succeed without any of the released resources, it should often be allowed to do so.

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).

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