At this point we have out application working, but the what if we would like the application to quit when we press the 'X' in the top right-hand corner of the window? Well we need to look at Window Events. If we look at the class Frame in the Java API documentation we can see that it has multiple parent classes. The API describes it as:
This means that any method that is available in the Window class or the Container class etc. is also present in the Frame class. If we read more in the API documentation we can see that:
So, the events are associated with the Window class (as they are WindowEvents) and if we go down we can see: Since: JDK1.0 See Also: WindowEvent , Window.addWindowListener(java.awt.event.WindowListener) , Serialized Form That we should look at the addWindowListener() method, which expects an object that has implemented the WindowListener interfaces. This interface is described as having the following methods that you must implement:
So, let us modify our previous code so that the when the window activates that the scroll value is set back to 50 and when the 'X' in the top right-hand side is clicked that the program exits. So, we want to implement the WindowListener interface on our class. Unfortunately, we have to implement all 7 methods or our code will not compile. So, we will add custom code for windowClosing() to exit our application and custom code for windowActivated() to set the value to 50 every time you activate the window (e.g. maximising after minimising). The code looks like this:
Now if you use the 'X' on the top right-hand corner the program exits and if you minimise and then maximise you will see the value reset to 50. These notes are copyright Dr. Derek Molloy, School of Electronic Engineering, Dublin City University, Ireland 2013-present. Please contact him directly before reproducing any of the content in any way. |