Javax.swing Class JOptionPane Java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JOptionPane.

Slides:



Advertisements
Similar presentations
1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while.
Advertisements

Graphic User Interfaces Layout Managers Event Handling.
Deitel Ch 11-part 1 Java GUIs 1 Java GUIs (Deitel, Chap 14-part1) Focus: Attaching GUI components + event handling  input dialog => only one value for.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Event Handling Events and Listeners Timers and Animation.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
Event-Driven Programming
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
GUI and Event-Driven Programming Part 2. Event Handling An action involving a GUI object, such as clicking a button, is called an event. The mechanism.
Java Programming Chapter 10 Graphical User Interfaces.
Chapter 9: Applets Jim Burns Fall Outline Learn about applets Learn about applets Write an HTML doc to host an applet Write an HTML doc to host.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 14 Event-Driven Programming.
Dale Roberts GUI Programming using Java - Event Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
 2002 Prentice Hall, Inc. All rights reserved Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Omer Boyaci.  GUIs are event driven.  When the user interacts with a GUI component, the interaction—known as an event—drives the program to perform.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Anonymous Classes An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression.
Object Oriented Programming.  Interface  Event Handling.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Graphical User Interface (GUI)
1 Lecture 8: User Interface Components with Swing.
Jozef Goetz Credits: Copyright  Pearson Education, Inc. All rights reserved. expanded by J. Goetz, 2016.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
GUIs & Event-Driven Programming Chapter 11 Review.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
© Copyright by Pearson Education, Inc. All Rights Reserved. Appendix I GUI Components and Event Handling Android How to Program, 3/e.
GUI Programming using Java - Event Handling
Lecture 15 Basic GUI programming
GUIs and Events Rick Mercer.
CSC 205 Programming II Lecture 5 AWT - I.
CompSci 230 S Programming Techniques
Introduction to Graphics
Java FX: Scene Builder.
3 Introduction to Classes and Objects.
Appendix I GUI Components and Event Handling
A First Look at GUI Applications
Introduction to Event Handling
Advanced Programming in Java
Constructors, GUI’s(Using Swing) and ActionListner
Presentation transcript:

javax.swing Class JOptionPane Java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent javax.swing.JOptionPane

Some basic Swing GUI components JOptionPanemore elaborate user interfaces Though it’s possible to perform input and output using the JOptionPane dialogs, most GUI applications require more elaborate user interfaces

Text Fields and an Introduction to Event Handling with Nested Classes

Event Handler&Event Handling  A user interacts with an application’s GUI to indicate the tasks that the application should perform.  For example, when you write an in an application, clicking the Send button tells the application to send the to the specified addresses.  GUIs are event driven.  When the user interacts with a GUI component, the interaction—known as an event—drives the program to perform a task.  Some common user interactions that cause an application to perform a task include:  clicking a button,  typing in a text field,  selecting an item from a menu,  closing a window and  moving the mouse.  The code that performs a task in response to an event is called an event handler, and the process of responding to events is known as event handling.

GUI Components: JTextField and JPasswordField Two other GUI components that can generate events are JTextField s and JPasswordField s (package javax.swing).  Class JTextField extends class JTextComponent (package javax.swing.text)  provides many features common to Swing’s text-based components.  Class JPasswordField extends JTextField and adds methods that are specific to processing passwords.  Each of these components is a single-line area in which the user can enter text via the keyboard. Applications can also display text in a JTextField  A JPasswordField shows that characters are being typed as the user enters them  but hides the actual characters with an echo character, assuming that they represent a password that should remain known only to the user  When the user types in a JTextField or a JPasswordField, then presses Enter, an event occurs.

Performing a Task  How a program can perform a task in response to that event. The techniques shown here are applicable to all GUI components that generate events.  The application uses classes JTextField and JPasswordField to create and manipulate four text fields.  When the user types in one of the text fields, then presses Enter, the application displays a message dialog box containing the text the user typed.  You can type only in the text field that’s “in focus.”  When you click a component, it receives the focus.  This is important, because the text field with the focus is the one that generates an event when you press Enter. In this example, when you press Enter in the JPasswordField, the password is revealed. We begin by discussing the setup of the GUI, then discuss the event- handling code.

Creating the GUI setLayout(new FlowLayout()); sets the TextFieldFrame’s layout to FlowLayout. textField1 = new JTextField(10); creates textField1 with 10 columns of text.  A text column’s width in pixels is determined by the average width of a character in the text field’s current font.  When text is displayed in a text field and the text is wider than the field itself, a portion of the text at the right side is not visible.  If you’re typing in a text field and the cursor reaches the right edge, the text at the left edge is pushed off the left side of the field and is no longer visible.  Users can use the left and right arrow keys to move through the complete text.

Creating the GUI add(textField3); adds textField3 to the JFrame. passwordField = new JPasswordField("Hidden text"); creates passwordField with the text "Hidden text" to display in the text field. The width of the field is determined by the width of the default text. When you execute the application, notice that the text is displayed as a string of asterisks. add(passwordField); adds passwordField to the JFrame.

Creating the GUI add(textField1); adds textField1 to the JFrame. textField2 = new JTextField("Enter text here"); creates textField2 with the initial text "Enter text here" to display in the text field. The width of the field is determined by the width of the default text specified in the constructor. add(textField2); add(textField2); adds textField2 to the JFrame. textField3 = new JTextField("Uneditable text field", 21); creates textField3 and calls the JTextField constructor with two arguments— the default text "Uneditable text field" to display and the text field’s width in columns (21).textField3.setEditable(false); uses method setEditable (inherited by JTextField from class JTextComponent) to make the text field uneditable—i.e., the user cannot modify the text in the field.

Steps Required to Set Up Event Handling for a GUI Component Enter  This example should display a message dialog containing the text from a text field when the user presses Enter in that text field.  Before an application can respond to an event for a particular GUI component, you must:  Create a class that represents the event handler and implements an appropriate interface known as an event-listener interface For instance: public class TextFieldFrame extends JFrame  Indicate that an object of the class from previous should be notified when the event occurs known as registering the event handler.

Using a Nested Class to Implement an Event Handler  All the classes discussed so far were so-called top-level classes  They were not declared inside another class.  Java allows you to declare classes inside other classes  These are called nested classes.  Nested classes can be static or non-static.  Non-static nested classes are called inner classes and are frequently used to implement event handlers.

Using a Nested Class to Implement an Event Handler  An inner-class object must be created by an object of the top-level class that contains the inner class.  Each inner-class object implicitly has a reference to an object of its top-level class.  The inner-class object is allowed to use this implicit reference to directly access all the variables and methods of the top-level class.

Using a Nested Class to Implement an Event Handler  A nested class that’s static  does not require an object of its top-level class  does not implicitly have a reference to an object of the top-level class.  the Java 2D graphics API uses static nested classes extensively.

Inner Class TextFieldHandler private inner class TextFieldHandler  The event handling in this example is performed by an object of the private inner class TextFieldHandler private class TextFieldHandler implements ActionListener  This class is private because it will be used only to create event handlers for the text fields in top-level class TextFieldFrame.  As with other class members, inner classes can be declared public, protected or private.  Since event handlers tend to be specific to the application in which they’re defined,  they’re often implemented as private inner classes or as anonymous inner classes

Inner Class TextFieldHandler  GUI components can generate many events in response to user interactions.  Each event is represented by a class and can be processed only by the appropriate type of event handler.  A component’s supported events are described in the Java API documentation for that component’s class and its superclasses.  When the user presses Enter in a JTextField or JPasswordField, an ActionEvent (package java.awt.event) occurs.  Such an event is processed by an object that implements the interface ActionListener (package java.awt.event).  Since JPasswordField is a subclass of JTextField, JPasswordField supports the same events.

How to Use Text Fields The Swing API provides several classes for components that are either varieties of text fields or that include text fields. JTextField : What this section covers: basic text fields. JFormattedTextField : A JTextField subclass that allows you to specify the legal set of characters that the user can enter. See How to Use Formatted Text Fields. JPasswordField: A JTextField subclass that does not show the characters that the user types. See How to Use Password Fields. JComboBox : Can be edited, and provides a menu of strings to choose from. See How to Use Combo Boxes. JSpinner : Combines a formatted text field with a couple of small buttons

An Example  The example displays a basic text field and a text area.  The text field is editable.  The text area is not editable.  When the user presses Enter in the text field  the program copies the text field's contents to the text area,  selects all the text in the text field.

ActionEvet public class ActionEvent extends AWTEvent  A semantic event which indicates that a component-defined action occurred.  This high-level event is generated by a component (such as a Button) when the component-specific action occurs (such as being pressed).  The event is passed to every ActionListener object that registered to receive such events using the component's addActionListener method. To invoke an ActionEvent on a Button using the keyboard, use the Space bar.  The object that implements the ActionListener interface gets this ActionEvent when the event occurs.  The listener is spared the details of processing individual mouse movements and mouse clicks, and can instead process a "meaningful" (semantic) event like "button pressed".  An unspecified behavior will be caused if the id parameter of any particular ActionEvent instance is not in the range from ACTION_FIRST to ACTION_LAST.

ActionEvet Field Summary static int ACTION_FIRST The first number in the range of ids used for action events. static int ACTION_LAST The last number in the range of ids used for action events. static int ACTION_PERFORMED This event id indicates that a meaningful action occured. static int ALT_MASK The alt modifier. static int CTRL_MASK The control modifier. static int META_MASK The meta modifier. static int SHIFT_MASK The shift modifier.

Inner Class  To prepare to handle the events,  I nner class TextFieldHandler implements interface ActionListener private class TextFieldHandler implements ActionListener  declares the only method in that interface— Override public void actionPerformed(ActionEvent event)  This method specifies the tasks to perform when an ActionEvent occurs.

Registering the Event Handler for Each Text Field In the TextFieldFrame constructor, TextFieldHandler handler = new TextFieldHandler(); creates a TextFieldHandler object and assigns it to variable handler. This object’s actionPerformed method will be called automatically when the user presses Enter in any of the GUI’s text fields. However, firstly the program must register this object as the event handler for each field. textField1.addActionListener(handler); textField2.addActionListener(handler); textField3.addActionListener(handler); passwordField.addActionListener(handler); The event-registration statements above specify handler as the event handler for the three JTextFields and the JPasswordField.

 The application calls JTextField method addActionListener to register the event handler for each component.  This method receives as its argument an ActionListener object, ActionListener.  This can be an object of any class that implements ActionListener. ActionListener,  The object handler is an ActionListener, because class TextFieldHandler implements ActionListener.  Then, the object handler listens for events.  when the user presses Enter in any of these four text fields, method actionPerformed in class TextFieldHandler is called to handle the event. public void actionPerformed(ActionEvent event) { …………………………………………..  If an event handler is not registered for a particular text field, the event that occurs when the user presses Enter in that text field is consumed  it’s simply ignored by the application.

Details of Class TextFieldHandler’s actionPerformed Method event-handling object’s actionPerformed  We use one event-handling object’s actionPerformed method to handle the events generated by four text fields.  It is required to output the name of each text field’s instance variable  we must determine which text field generated the event each time actionPerformed is called.  The event source is the component with which the user interacted. unique ActionEvent object  When the user presses Enter while a text field or the password field has the focus, the system creates a unique ActionEvent object  It contains information about the event that just occurred, such as the event source and the text in the text field.

actionPerformed Method public void actionPerformed(ActionEvent event)  The system passes this ActionEvent object to the event listener’s actionPerformed method. String string = "";  declares the String that will be displayed.  The variable is initialized with the empty string a String containing no characters. The compiler requires the variable to be initialized in case none of the branches of the nested if in lines 59– 76 executes.

ActionEvent Method getSource()  ActionEvent method getSource returns a reference to the event source. if (event.getSource() == textField1)…………………………… else if (event.getSource() == textField2)………………………. else if (event.getSource() == textField3)……………………. else if (event.getSource() == passwordField)……………………..  The condition if (event.getSource() == textField1) means “Is the event source textField1?” == This condition compares references with the == operator to determine if they refer to the same object.  If they both refer to textField1, the user pressed Enter in textField1.

The line string = String.format("textField1: %s", event.getActionCommand()); event.getActionCommand()); create a String containing the message that line JOptionPane.showMessageDialog(null, string); displays in a message dialog.

ActionEvent Method getActionCommand() event.getActionCommand()); uses ActionEvent method getActionCommand to obtain the text the user typed in the text field that generated the event.  We display the text of the password in the JPasswordField  when the user presses Enter in that field.  Sometimes it’s necessary to programatically process the characters in a password.  Class JPasswordField method getPassword returns the password’s characters as an array of type char.

Testing TextFieldFrame import javax.swing.JFrame; public class TextFieldTest { public static void main(String[] args) { TextFieldFrame textFieldFrame = new TextFieldFrame(); textFieldFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); textFieldFrame.setSize(350, 100); textFieldFrame.setVisible(true); }

Class TextFieldTest  Class TextFieldTest contains the main method that executes this application and displays an object of class TextFieldFrame.  When you execute the application, even the uneditable JTextField (textField3) can generate an ActionEvent.  To test this, click the text field to give it the focus, then press Enter.  the actual text of the password is displayed when you press Enter in the JPasswordField.  you would normally not display the password!

Conclusion  This application used a single object of class TextFieldHandler as the event listener for four text fields.  it’s possible to declare several event-listener objects of the same type and register each object for a separate GUI component’s event.  This technique enables us to eliminate the if...else logic used in this example’s event handler by providing separate event handlers for each component’s events.

public class FlowLayout extends Object implements LayoutManager, Serializable Constructors FlowLayout() Constructs a new FlowLayout with a centered alignment and a default 5- unit horizontal and vertical gap. FlowLayout(int align) Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap. FlowLayout(int align, int hgap, int vgap) Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps.

Using the Keyword super  Accessing Superclass Members  If the method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super.  Subclass Constructors  the super keyword to invoke a superclass's constructor.

Accessing Superclass Members using super keyword public class Superclass { public void printMethod() { public void printMethod() { System.out.println("Printed in Superclass."); } } public class Subclass extends Superclass { // overrides printMethod in Superclass public void printMethod() { public void printMethod() { super.printMethod(); System.out.println("Printed in Subclass"); } public static void main(String[] args) { Subclass s = new Subclass(); s.printMethod(); s.printMethod(); } }

Subclass Constructors using super keyword public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) { super(startCadence, startSpeed, startGear); seatHeight = startHeight; }  The super keyword to invoke a superclass's constructor.  the Bicycle is superclass and MountainBike is a subclass of Bicycle.  The MountainBike (subclass) constructor calls the superclass constructor and then adds initialization code of its own

import java.awt.FlowLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.JPasswordField; import javax.swing.JOptionPane; These are required for TextFieldFrame.java