Project won't stop running on NetBeans - java

I started writing a small program to learn a bit more about java and try to design my layouts by hand without always using NetBeans.
Thing is, when I run my project and close it, it won't stop running in NetBeans, so everytime I re-run it creates another run. By searching and looking at another GUI I had created using NetBeans I thought adding the
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
would do the trick, but I guess I am wrong.
Can someone please explain me what I should do?
Here is a SSCCE of my programa: http://pastebin.com/QhKpwdDw
Thank you very much in advance!

You might want to take a look at this question: How to close a Java Swing application from the code, as it deals with closing the application in general and also how to ensure it completely terminated.
But to answer your question quickly, there are a couple of options.
Option 1
Since you are extending JFrame in your class, you can just use EXIT_ON_CLOSE to quit.
setDefaultCloseOperation(EXIT_ON_CLOSE);
NOTE: EXIT_ON_CLOSE exits all JFrames in your application, not just the one it is applied to.
Option 2
This is most likely not the answer you want, but DISPOSE_ON_CLOSE will close only the JFrame you are applying it to.
If you have multiple JFrames open, or if you have any other Threads, they will keep running and the program will not end. But if you only have one Thread and one JFrame, this will close the application.
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
My Preference
I would go with Option 1, disagreeing with everyone else. It is directly tied to JFrame and not dependent on WindowConstants, which makes things cleaner and more reliable. But more importantly, it closes all of the windows, not just the one that you apply it to.
Even though it looks like you only have one window, you may have other internal Threads elsewhere in your program that NetBeans is throwing in there.
To be sure everything closes, you want to use EXIT_ON_CLOSE.
Extra Information
For a discussion on how DISPOSE_ON_CLOSE and EXIT_ON_CLOSE differ: http://www.coderanch.com/t/340183/GUI/java/DISPOSE-CLOSE-vs-EXIT-CLOSE
Documentation on JFrame's EXIT_ON_CLOSE: http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/JFrame.html#EXIT_ON_CLOSE
Documentation on DISPOSE_ON_CLOSE and other WindowConstants: http://docs.oracle.com/javase/1.5.0/docs/api/javax/swing/WindowConstants.html#DISPOSE_ON_CLOSE

setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/WindowConstants.html#DISPOSE_ON_CLOSE
DISPOSE_ON_CLOSE
public static final int DISPOSE_ON_CLOSE
The dispose-window default window close operation.
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.
See Also:
Window.dispose(), JInternalFrame.dispose(), Constant Field Values

Try this...
Place it inside the constructor of your JFrame or the class which extends JFrame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

As you can see here (setDefaultCloseOperation doc) you can use DISPOSE_ON_CLOSE if you want to trigger a window listener (for example to close a database connection).
In such a case it make sense to choose DISPOSE_ON_CLOSE instead of EXIT_ON_CLOSE.
PS : Don't forget although to add a System.exit(0) at the end of the window listener code, so that the application exits.

Related

Displaying information from multiple threads in a single JFrame

I start several(threads) instances of a java class that receives an "input" and based on that generates an "output" on out it out on the standard output(screen). I would like to add an option that would enable me to send this output to a single JFrame (text area). What is the best way of doing this? Up to this point my program was totally GUIless but I would like to make it a bit more GUI friendly and add this option.
The challenge is that at any given point I could have several threads running. Any design or code snippets would be greatly appreciated.
As MadProgrammer points out, a nice, encapsulated way of doing this is SwingWorker.
That said, here is the general theory:
All updates to Swing components must be done on the Swing event dispatch thread (there are some exceptions, but not relevant here). This is achieved by SwingUtilities.invokeLater() (and occasionally invokeAndWait() ).
The Swing runtime will then queue up the changes you want to make and call them one at a time. This makes the entire problem of updating your text area pretty trivial: just create a Runnable with the text you want to append, pass that to invokeLater(), and have your Runnable grab the document model of the text area and append your desired text to it.
SwingWorker can encapsulate some of the complexities of background thread management, but I encourage you to do it the 'hard way' a time or two (and your use-case is actually easier to do the 'hard way'). That way you can appreciate what SwingWorker does for you when you do need it.
You need not to convert your existing threads to SwingWorkers. Just let them from time to time send messages to JFrame in a way like this:
EventQueue.invokeLater(new Runnable(){
// update GUI
});
To avoid boilerplate code, it is good to wrap programming interface to the screen with a java.lang.reflect.Proxy. An example of such wrapping is at SwingProxyActorTest.java.

Multiple Applets - stop() and destroy()

I have a page with multiple applets (yes, it's old). One of these applets overrides the stop method, as follows:
#Override public void stop() {
System.out.println("Stop called!");
}
But, when I do this, nothing is displayed in the console (yes, the java console) when I switch tabs, or do anything else that should call stop(). The same problem is happening with overriding destroy(). However, the start() and init() functions work as expected.
My applets are extending another class, which in turn extends JApplet. I did this to give all of my applets access to specific functions (defined in this in-between class). These applets also create other threads for repetitive tasks, but I don't think that should affect the life cycle methods. I'm not sure where to look at this point, is it possible that the focus functions or something else like that is preventing the lifecycle methods from executing, or does having multiple applets on one page cause problems with these methods? Thanks beforehand.
EDIT: I have posted a SSCCE on my server to show this behaviour Click here to run and Here to dowload sources, it's a simple applet that starts a thread, which calls a method in the parent applet that opens a JDialog. You'll notice that you can close the browser tab while the dialog is open (as long as there are other tabs open) and neither the stop or destroy print statements will occur in IE10. On top of that, the JVM keeps running, and the Java console does not close. However, if you acknowledge the pop-up before closing the browser window, everything functions as expected.
So, the question then, is if someone closes the browser window while a popup is open, how do I kill the extra thread, and the pop-up itself?
The JDialog mentioned is created using JOptionPane. Quoting from the javadoc
All dialogs are modal
Modal dialogs effectively block the applet preventing the stop and destroymethods in the applet from being called. You could simply make the dialog non-modal
popup.setModal(false);
After downloading and expanding the Zip, and turning the 2 sources into an SSCCE (an SSCCE is one source file by definition), I noted the same behavior in IE9.
It seems to me this is yet another example of a browser/JVM interaction bug. In FF the user is unable to close the page or change tabs when the dialog is open. That leads to a behavior that is as we'd expect, since the dialog must be closed prior to the applet tab being closed (or tab change or the browser being closed).
In IE9 (and 10, according to your report), the page can be accessed despite the visibility of the dialog, leading to all the problems.
Unfortunately the only work-around I could think of, didn't (work). Sometimes the necessary event can be detected by a ComponentListener, but in this case, it does not fire on closing the tab or changing tab.
So, I suggest you search the bug database for anything similar. If you find nothing, raise a new report and see what Oracle has to say on the matter. If it is a bug and they think it is the fault of IE, they can take it up with MS.
I switch tabs, or do anything else that should call stop(). The same
problem is happening with overriding destroy(). However, the start()
and init() functions work as expected.
Life Cycle of an Applet Doc page says:
When the user leaves the page, for example, to go to another page, the browser stops and destroys the applet. The state of the applet is not preserved. When the user returns to the page, the browser intializes and starts a new instance of the applet.
So yes I am having the correct result when i try to change the page on which applet is running, the stop() and destroy() method gets called and stopping and destroying gets printed. If by switching the tab you are meaning selecting one tab among the opened tabs, this is not to cause stop() and destroy() get called. However if you run JApplet directly from an applet viewer using Netbeans/Eclipes you will see that window state change(e.g., iconified, normalized) will cause stop() get called. destroy() will be called if you close the JApplet viewer.
You'll notice that you can close the browser tab while the dialog is open (as long as there are other tabs open) and neither the stop or destroy print statements will occur in IE10.
well i have tested with IE9 as i don't have IE10 now, i noticed in IE9 unlike in Firefox that the JDialouge lets switching tab among the opened tabs but it let neither the browser nor the page containing the applet get closed until acknowledging it. So it has something to do with IE10. you can try to use javascript to call an applet function to force it to be exited on window close event. I am not sure about this though as i mentioned, i don't have IE10.
On top of that, the JVM keeps running, and the Java console does not close. However, if you acknowledge the pop-up before closing the browser window, everything functions as expected.
I am a little bit confused here. Actually both Firefox and in IE9, i have experienced that after closing the page containing JApplet, jp2launcher.exe takes at most 2 mins time to exit itself and java.exe. In the mean time if you reopen the page containing the applet, it will start instantly without asking for any permission as it would ask first time when it got loaded.

First call to JFrame constructor takes a long time during Swing application startup (because of java.awt.Window())

I'm trying to build a simple, lightweight, and responsive application using Java Swing.
When it launches, however, there is a noticeable delay (>500ms) before the window (a JFrame) appears.
I've tracked it down to the constructor of the java.awt.Window class, which is an ancestor of JFrame.
Oddly, the constructor is only slow for the first call. If I create multiple JFrame objects, the time spent in the constructor is ~600ms for the first object, but is typically measured as 0ms for subsequent objects.
Here's a simple example which, on my system, shows this significant delay for the first constructor call but not the second:
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
long start;
start = System.currentTimeMillis();
JFrame frame1 = new JFrame();
System.out.println((System.currentTimeMillis() - start) + " for first JFrame.");
start = System.currentTimeMillis();
JFrame frame2 = new JFrame();
System.out.println((System.currentTimeMillis() - start) + " for second JFrame.");
}
});
}
With typical output:
641 for first JFrame.
0 for second JFrame.
If I add this Window object initialization before the JFrame objects:
java.awt.Window window = new java.awt.Window(null);
Then the output changes to something like:
578 for first Window.
47 for first JFrame.
0 for second JFrame.
When I try the same with the superclass of Window, java.awt.Container, the Window constructor is still the one that takes a long time to execute (so the problem doesn't go above the Window class).
Since the JFrame constructor calls the Window constructor, the above seems to indicate that the first call to the Window constructor is expensive.
What happens in the first call to the constructor that takes so long, and is there anything I can do about it?
Is there some simple fix or is the problem fundamental to Swing/AWT? Or is it perhaps a problem specific to my system/setup?
I'd like my application to open as fast (or nearly as fast) as MS Notepad, and, while I can have text printed to the console around the time Notepad opens (if I put the code before the first JFrame initialization), the above problem means that there is almost a whole second of delay before the window is visible. Will I need to use a different language or GUI framework to get the performance I'm after?
Edit: If I add Thread.sleep(10000) as the first line of run(), the results don't change (they just appear 10 seconds later). This suggests that the problem is not caused by some asynchronous startup code but is instead triggered directly by the constructor call.
Edit 2: Realized the NetBeans Profiler can profile inside the JRE classes, and discovered that most of the time is spent initializing a sun.java2d.d3d.D3DGraphicsDevice object (the Window object needs screen bounds and insets), which is part of a "Direct3D Accelerated Rendering Pipeline for Microsoft Windows Platforms, Enabled by Default", introduced in Java 6u10. It can be disabled by passing the "-Dsun.java2d.d3d=false" property to the JVM, which does reduce the startup time by about 3/4, but I'm not yet sure if I'll need it (D3D) or if there's some other way to get it to load faster.
Here is the output if I put that parameter on the command line:
0 for first Window
47 for first JFrame.
0 for second JFrame.
I'll come back and clean this post up after I dig deeper later.
This answer records what I have found so far. If anyone has more information, please comment or post an answer. I am not completely satisfied with simply disabling Swing's use of D3D, and am open to other solutions.
The Cause: D3D Initialization
Swing uses the Java2D API for drawing, and according to this Java SE 7 troubleshooting guide, Java2D uses a set of rendering pipelines, "which can be roughly defined as different ways of rendering the primitives". More specifically, a Java2D rendering pipeline seems to connect cross-platform Java code to native graphics libraries (OpenGL, X11, D3D, DirectDraw, GDI) that may support hardware acceleration.
In Java 1.6.0_10 (aka 6u10), a "fully hardware accelerated graphics pipeline" based on Direct3D was added to Java2D for Windows to improve rendering performance in Swing and Java2D applications (enabled by default).
By default, when Java2D is used on a Windows system, both this Direct3D pipeline and a DirectDraw/GDI pipeline are enabled by default (I assume they are each being used for different things).
The D3D library, at least, is only loaded and initialized when needed, and a native D3D initialization function which gets called the first time a Window (or a Window descendant) is constructed takes ~500ms (for me) and causes the reported slowness of initialization, and disabling the D3D pipeline seems to remove the call to this native function, significantly decreasing startup time. (Although I'd much prefer to delay, precompute, share (across different java apps), or optimize the D3D initialization, and I wonder if it's this slow for other languages.)
Granted, it's possible that on most systems the time spent in D3D init is negligible, and it is only a problem on my system due to some hardware or driver problem, but I'm somewhat skeptical of this (although, if true, that would be an easy fix).
Detailing the trace down to the native initD3D()
In more detail (skip the following paragraph if you don't care), I used the Netbeans profiler and debugger to find that:
When a JFrame is initialized (constructor called), the constructor of ancestor class java.awt.Window gets called. The Window initializes its GraphicsConfiguration device, which tries to retrieve the default screen device, and so on. The first time this happens (when the first Window or Window descendant is initialized), the screen device doesn't exist, so it is built. In this process, the sun.java2D.d3d.D3DGraphicsDevice class gets initialized, and in its static initialization block (see <clinit>()) it calls a native function, initD3D(), which takes a significant time to execute (~500ms).
I was able to find a version of the source code for D3DGraphicsDevice and its static init block (and I'm really just assuming from this source that initD3D() is what makes its <clinit>() take so long - my profiler doesn't seem to acknowledge native functions - but it's a reasonable guess).
One workaround - disable D3D for Java2D
The D3D pipeline can be disabled by running java with the -Dsun.java2d.d3d=false option, as per this guide on Java2D "system properties" (and also the aforementioned troubleshooting guide). I think this disables D3D but not DirectDraw, which can be disabled with Dsun.java2d.noddraw=true (and then "all operations will be performed with GDI"), but this doesn't noticeably improve initialization time.
For example, I might use a command like the following to run MyJar.jar without D3D:
java -jar -Dsun.java2d.d3d=false MyJar.jar
With the code posted in the question (which initializes a Window and then 2 JFrame objects), I get results like this:
0 for first Window
47 for first JFrame.
0 for second JFrame.
Instead of results like this:
547 for first Window
31 for first JFrame.
0 for second JFrame.
(Note that time is in milliseconds and is measured with System.currentTimeMillis() on Windows, which I think has a resolution of around 15 to 16 ms.)
OpenGL vs Direct3D
OpenGL is used instead of Direct3D if the -Dsun.java2d.opengl=True option is used. On my system there is a slight improvement (~400ms for OpenGL vs ~500ms for D3D), but the delay is still noticeable.
Other Delays
I noticed that initialization of the first JFrame object, even if it is not the first Window, takes much more time than the initialization of subsequent JFrame objects (recorded as 31 to 47 ms vs 0ms).
Profiling indicates this is related to the creation of the first glass pane (a JPanel), and ultimately seems to be caused by Look and Feel and system property intialization/loading inside the javax.swing.UIManager class and object initialization code. It's not too important, but it does explain the observed anomaly.
In my actual program which is a bit more complicated (has to initialize more Swing components), delays seem to be more diffusely distributed in the Swing code, but I've noticed a significant amount of native class loading, "UI installing" (loading default UI properties, etc.), and such. Unfortunately, I don't think there's much to be done about these (please speak up if there is).
Closing thoughts
In the end, there's only so much that can be done, and I have to recognize how far Swing and the JVM have come in the past years.
The creation of the first jframe involves loading the swing library. JVM doesn't load the library looking at the import statement. The libraries are loaded only when the first call to that library is made.
In this case frame1 creation is the first statement that calls the Swing library. By the time frame2 instance is created the swing libraries are already loaded and hence the object creation for frame2 is too fast even to notice some lapse of time. Hence it shows 0.
This explains why it shows 578, 47, 0 when you add up Window statement above the two. This is because the first statement takes time to load java.awt library. Second takes time to load the swing library. And the thirds shows 0 as the library needed for its creation is already loaded.
You can even test it this way. Try to replace the second JFrame creation with JPanel and it still it shows 0.
My guess is that it's loading native libraries. If this is the case, there is not much you can do about it.
Mac OS X 10.5.8, Java 1.6.0_26. Not unexpected, given the JVM startup time and heavyweight graphics peer creation.
247 for first JFrame.
0 for second JFrame.
Addendum: According to the article Java Performance: Startup time, Java Quick Starter may be available on your platform.
It takes time to load all swing classes, then it takes time to load native awt libraries. Perhaps, class loading takes more time because if you just create a JLabel instead of the first JFrame it still takes more time.

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

Calling function when program exits in java

I would like to save the programs settings every time the user exits the program. So I need a way to call a function when the user quits the program. How do I do that?
I am using Java 1.5.
You can add a shutdown hook to your application by doing the following:
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
// what you want to do
}
}));
This is basically equivalent to having a try {} finally {} block around your entire program, and basically encompasses what's in the finally block.
Please note the caveats though!
Adding a shutdown hook addShutdownHook(java.lang.Thread) is probably what you look for. There are problems with that approach, though:
you will lose the changes if the program aborts in an uncontrolled way (i.e. if it is killed)
you will lose the changes if there are errors (permission denied, disk full, network errors)
So it might be better to save settings immediately (possibly in an extra thread, to avoid waiting times).
Are you creating a stand alone GUI app (i.e. Swing)?
If so, you should consider how you are providing options to your users how to exit the application.
Namely, if there is going to be a File menu, I would expect that there will be an "Exit" menu item.
Also, if the user closes the last window in the app, I would also expect it to exit the application.
In both cases, it should call code that handles saving the user's preferences.
Using Runtime.getRuntime().addShutdownHook() is certainly a way to do this - but if you are writing Swing applications, I strongly recommend that you take a look at JSR 296 (Swing Application Framework)
Here's a good article on the basics: http://java.sun.com/developer/technicalArticles/javase/swingappfr/.
The JSR reference implementation provides the kind of features that you are looking for at a higher level of abstraction than adding shutdown hooks.
Here is the reference implementation: https://appframework.dev.java.net/

Categories