If you click the buttons at this point, nothing happens. I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time. Pearson Education, Inc. This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site.
Please note that other Pearson websites and online products and services have their own separate privacy policies. To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:. For inquiries and questions, we collect the inquiry or question, together with name, contact details email address, phone number and mailing address and any other additional information voluntarily submitted to us through a Contact Us form or an email.
We use this information to address the inquiry and respond to the question. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes. Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites.
Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey. Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing.
Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law. If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information informit.
On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature. We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.
Pearson automatically collects log data to help ensure the delivery, availability and security of this site. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.
The information gathered may enable Pearson but not the third party web trend services to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.
Disabling or blocking certain cookies may limit the functionality of this site. Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure. Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.
If a user's personally identifiable information changes such as your postal address or email address , we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service informit.
Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list s simply visit the following page and uncheck any communication you no longer want to receive: www. While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest pearson. California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice.
The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services. This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information.
This privacy statement applies solely to information collected by this web site. Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information. We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting.
Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.
FREE U. Walks you through how to use Swing to create applications that feature key GUI components. This chapter is from the book. NOTE If you click the buttons at this point, nothing happens. Overview Pearson Education, Inc. Collection and Use of Information To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including: Questions and Inquiries For inquiries and questions, we collect the inquiry or question, together with name, contact details email address, phone number and mailing address and any other additional information voluntarily submitted to us through a Contact Us form or an email.
Surveys Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Contests and Drawings Occasionally, we may sponsor a contest or drawing. Newsletters If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information informit. Service Announcements On rare occasions it is necessary to send out a strictly service related announcement.
Customer Service We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form. Other Collection and Use of Information Application and System Logs Pearson automatically collects log data to help ensure the delivery, availability and security of this site.
Security Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure. Children This site is not directed to children under the age of Marketing Pearson may send or direct marketing communications to users, provided that Pearson will not use personal information collected or processed as a K school service provider for the purpose of directed or targeted advertising.
Such marketing is consistent with applicable law and Pearson's legal obligations. Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing. Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn. Sale of Personal Information Pearson does not rent or sell personal information in exchange for any payment of money.
Supplemental Privacy Statement for California Residents California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. Sharing and Disclosure Pearson may disclose personal information, as follows: As required by law.
Links This web site contains links to other sites. A KeyEvent is fired when you pressed, released, and typed pressed followed by released a key on the source object. A KeyEvent listener must implement KeyListener interface, which declares three abstract methods:. This class shall implement ActionListener interface and override the actionPerformed method. An example is as follows:. Can you see the problem? We can fix this problem, but the solution is messy.
An easy solution is to use an inner class instead of an ordinary external class to be explained in the following sections. A nested class or commonly called inner class is a class defined inside another class - introduced in JDK 1. A nested class is useful if you need a small class which relies on the enclosing outer class for its private variables and methods. It is ideal in an event-driven environment for implementing event handlers. This is because the event handling methods in a listener often require access to the private variables e.
BtnCountListener needs to be defined as an inner class, as it needs to access private variables count and tfCount of the outer class. Try moving the BtnCountListener class outside, and define it as an ordinary class. You would need to pass a reference of the AWTConnter into the constructor of BtnCountListener , and use this reference to access variables tfCount and count , through public getters or granting them to public access.
Instead of using a named inner class called BtnCountListner in the previous example , we shall use an inner class without a name, known as anonymous inner class as the ActionListener in this example. Let's modify our AWTCounter example to include 3 buttons for counting up, counting down, and reset the count, respectively. We shall attach an anonymous inner class as the listener to each of buttons.
If you use the same instance as the listener for all the 3 buttons, you need to determine which button has fired the event. It is because all the 3 buttons trigger the same event-handler method. In the following example, we use the same instance of a "named" inner class as the listener for all the 3 buttons. The listener needs to determine which button has fired the event. This can be accomplished via the ActionEvent 's getActionCommonad method, which returns the button's label.
Besides the getActionCommand , which is only available for ActionEvent , you can use the getSource method, which is available to all event objects, to retrieve a reference to the source object that has fired the event. You may need to downcast it to the proper type of the source object. Refer to the WindowEventDemo , a WindowEvent listener is required to implement the WindowListener interface, which declares 7 abstract methods.
Although we are only interested in windowClosing , we need to provide an empty body to the other 6 abstract methods in order to compile the program. This is tedious, e. An adapter class called WindowAdapter is therefore provided, which implements the WindowListener interface and provides default implementations to all the 7 abstract methods.
You can then derive a subclass from WindowAdapter and override only methods of interest and leave the rest to their default implementation. There is no ActionAdapter for ActionListener , because there is only one abstract method i. This method has to be overridden and there is no need for an adapter. If you read some old books, you may find many examples that use " this " object as the event listener.
There is only ONE class in this code. But this code is much harder to understand and seldom used nowadays. Using inner class is a better solution. A container has a so-called layout manager to arrange its components. The layout managers provide a level of abstraction to map your user interface on all windowing systems, so that the layout can be platform-independent. AWT provides the following layout managers in package java.
Swing added more layout manager in package javax. Panel and Swing's JPanel provides a constructor to set its initial layout manager. It is because a primary function of Panel is to layout a group of component in a particular layout. In the java. FlowLayout , components are arranged from left-to-right inside the container in the order that they are added via method aContainer.
When one row is filled, a new row will be started. The actual appearance depends on the width of the display window. In java. GridLayout , components are arranged in a grid matrix of rows and columns inside the Container. Components are added in a left-to-right, top-to-bottom manner in the order they are added via method aContainer. Components are added using method aContainer. You need not place components to all the 5 zones.
An AWT Panel is a rectangular pane, which can be used as sub-container to organized a group of related components in a specific layout e. Panel s are secondary containers, which shall be added into a top-level container such as Frame , or another Panel.
BoxLayout arrange components in a single row or column. It respects components' requests on the minimum sizes. JFC consists of:. JDK 1. Swing appeared after JDK 1. It was introduced into JDK 1. Swing is a rich set of easy-to-use, easy-to-understand JavaBean GUI components that can be dragged and dropped as "GUI builders" in visual programming environment. Swing is now an integral part of Java since JDK 1. Swing is huge consists of 18 packages of classes as in JDK 1.
Compared with the AWT component classes in package java. The above figure shows the class hierarchy of the swing GUI classes. Similar to AWT, there are two groups of classes: container s and component s. A container is used to hold components. A container can also hold containers because it is a subclass of component. As a rule, do not mix heavyweight AWT components and lightweight Swing components in the same program, as the heavyweight components will always be painted on top of the lightweight components.
Just like AWT application, a Swing application requires a top-level container. There are three top-level containers in Swing:. Similarly to AWT, there are secondary containers such as JPanel which can be used to group and layout relevant components. The JComponents must be added onto the so-called content-pane of the top-level container.
Content-pane is in fact a java. Container that can be used to group and layout components. Notes: If a component is added directly into a JFrame , it is added into the content-pane of JFrame instead, i. Swing uses the AWT event-handling classes in package java.
Swing introduces a few new event-handling classes in package javax. Let's convert the earlier AWT application example into Swing. Compare the two source files and note the changes which are highlighted. The display is shown below. The JFrams 's method getContentPane returns the content-pane which is a java. Containter of the JFrame. You can then set its layout the default layout is BorderLayout , and add components into it.
Instead of writing a WindowEvent listener with a windowClosing handler to process the "close-window" button, JFrame provides a method called setDefaultCloseOperation to sets the default operation when the user initiates a "close" on this frame. Typically, we choose the option JFrame. In the previous examples, we invoke the constructor directly in the entry main method to setup the GUI components. The constructor will be executed in the so-called "Main-Program" thread.
This may cause multi-threading issues such as unresponsive user-interface and deadlock. It is recommended to execute the GUI setup codes in the so-called "Event-Dispatching" thread, instead of "Main-Program" thread, for thread-safe operations. Event-dispatching thread, which processes events, should be used when the codes updates the GUI.
To run the constructor on the event-dispatching thread, invoke static method SwingUtilities. The codes will be run after all pending events have been processed. Note: javax. At times, for example in game programming, the constructor or the main may contains non-GUI codes. This GUI init method shall be run in the event-dispatching thread. This warning message is triggered because java. Frame via its superclass java. Component implements the java. Serializable interface. This interface enables the object to be written out to an output stream serially via method writeObject ; and read back into the program via method readObject.
The serialization runtime uses a number called serialVersionUID to ensure that the object read into the program is compatible with the class definition, and not belonging to another version. Introduction So far, we have covered the basic programming constructs such as variables, data types, decision, loop, array and method and introduced the important concept of Object-Oriented Programming OOP. The java. Custom graphics classes, such as Graphics , Color and Font.
They are also called widgets , controls in other graphics systems. A container can also hold sub-containers. To write a GUI program, we typically start with a subclass extending from java. Frame to inherit the main window as follows: import java. A Dialog has a title-bar containing an icon, a title and a close button and a content display area, as illustrated. An AWT Applet in package java. Applet is no longer supported in most of the browsers. Secondary Containers: Panel and ScrollPane Secondary containers are placed inside a top-level container or another secondary container.
AWT provides these secondary containers: Panel : a rectangular box used to layout a set of related GUI components in pattern such as grid or flow. Label A java. Note that three static constants Label. LEFT , Label.
CENTER are defined in the class for you to specify the alignment rather than asking you to memorize arbitrary integer values. The second constructor constructs a Label object with the given text string in default of left-aligned. The third constructor constructs a Label object with an initially empty string. You could set the label text via the setText method later. LEFT, Label. Constructing a Component and Adding the Component into a Container Three steps are necessary to create and place a GUI component: Declare the component with an identifier name ; Construct the component by invoking an appropriate constructor via the new operator; Identify the container such as Frame or Panel designed to hold this component.
The container can then add this component onto itself via aContainer. Every container has a add Component method. Take note that it is the container that actively and explicitly adds a component onto itself, NOT the other way. Button A java. Disabled Button cannot be clicked. Event Clicking a button fires a so-called ActionEvent and triggers a certain programmed action. TextField A java.
Each time you click the button, the counter's value increases by 1. Dissecting the AWTCounter. In other words, this class AWTCounter is a Frame , and inherits all the attributes and behaviors of a Frame , such as the title bar and content pane. Lines 11 to 47 define a constructor, which is used to setup the GUI components and event handlers. In Line 13, the setLayout inherited from the superclass Frame is used to set the layout of the container.
FlowLayout is used which arranges the components in left-to-right and flows into next row in a top-to-bottom manner. A Label , TextField non-editable , and Button are constructed. We invoke the add method inherited from the superclass Frame to add these components into container. In Line , we invoke the setSize and the setTitle inherited from the superclass Frame to set the initial size and the title of the Frame. The setVisible true method Line 42 is then invoked to show the display.
Line is used to setup the callback event-handler, which will be discussed in length later. In brief, whenever the button is clicked, the actionPerformed will be called. In the actionPerformed Lines , the counter value increases by 1 and displayed on the TextField. The constructor is executed to initialize the GUI components and setup the event-handlers. The GUI program then waits for the user action.
For example, if we insert the following code before and after the setvisible : System. Frame Line 6 - the top-level window container. In the constructor Line 14 , we constructs 4 components - 2 anonymous java. Label s and 2 java. TextField s. The Frame adds the components, in GridLayout. The listener class needs to implement ActionListener interface and provides implementation to method actionPerformed.
The sequence of steps is illustrated above: The source object registers its listener s for a certain type of event. The source is triggered by a user. The source create a XxxEvent object, which encapsulates the necessary information about the activation. For example, the x, y position of the mouse pointer, the text entered, etc. Finally, for each of the XxxEvent listeners in the listener list, the source invokes the appropriate handler on the listener s , which provides the programmed response.
The listener s is required to implement ActionListener interface, and override the actionPerformed method to provide the response. In Line , we write an inner class called BtnCountListener , which override the actionPerformed to increment and display the count. An inner class is a class defined inside an outer class, and it can access the private entities of the outer class. We will elaborate on the inner class in the next section. The source object registers listener via the addActionListener.
The ActionEvent listener is required to implement the ActionListener interface, and override the actionPerformed method to provide the programmed response upon activation. We identify the super Frame as the source object. It is required to implement the WindowListener interface, which declares 7 abstract methods: windowOpened , windowClosed , windowClosing , windowActivated , windowDeactivated , windowIconified and windowDeiconified.
We override the windowClosing handler to terminate the program using System. We ignore the other 6 handlers, but required to provide an empty body for compilation. The sequence diagram is as follow: Example 4: MouseEvent and MouseListener Interface A MouseEvent is fired when you press, release, or click press followed by release a mouse-button left or right button at the source object; or position the mouse-pointer at enter and away exit from the source object.
To demonstrate the MouseEvent : We identity super Frame as the source object. It is required to implement the MouseListener interface, which declares 5 abstract methods: mouseClicked , mousePressed , mouseReleased , mouseEntered , and mouseExit. We override the mouseClicked to display the x, y coordinates of the mouse click on the two displayed TextField s. We ignore all the other handlers for simplicity - but you need to provide an empty body for compilation.
We override the mouseMoved to display the x, y position of the mouse pointer. We ignore the MouseDragged handler by providing an empty body for compilation. Example 6: KeyEvent and KeyListener Interface A KeyEvent is fired when you pressed, released, and typed pressed followed by released a key on the source object. The KeyEvent listener needs to implement the KeyListener interface, which declares 3 abstract methods: keyTyped , keyPressed , keyReleased.
We override the keyTyped to display key typed on the display TextArea. We ignore the keyPressed and keyReleased.