Unit 101 Java GUI Components and Events  GUI Components and Containers  Adding Components to Containers  GUI Events  GUI Events Classes  Learning.

Slides:



Advertisements
Similar presentations
Graphic User Interfaces Layout Managers Event Handling.
Advertisements

1 Chapter 12 l Event-Driven Programming and GUIs l Swing Basics and a Simple Demo Program l Layout Managers l Buttons and Action Listeners l Container.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
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.
Unit 111 Event-Driven Programming Listener or Event handler Example: Handling Button Events Example: Handling Mouse Events Example: Handling Keyboard Events.
Event-Driven Programming
GUI and Event-Driven Programming Recitation – 3/6/2009 CS 180 Department of Computer Science, Purdue University.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
Unit 111 Java GUI Components and Events  Learning Outcomes oDistinguish between GUI components and containers. oIdentify and distinguish top-level containers.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
1 Class 8. 2 Chapter Objectives Use Swing components to build the GUI for a Swing program Implement an ActionListener to handle events Add interface components.
Lesson 35: Review of the Java GUI. The JFrame, Container and JButton.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
GUI programming Graphical user interface-based programming.
Introduction to Swing Components Chapter 14.  Part of the Java Foundation Classes (JFC)  Provides a rich set of GUI components  Used to create a Java.
GUI Chapter 10 Graphics context and objects Creating a window based application JFrame, JTextField, JButton Containers and Controls Graphics commands Layout.
Chapter 9: Visual Programming Basics Object-Oriented Program Development Using Java: A Class-Centered Approach.
Lesson 34: Layering Images with Java GUI. The FlowLayout RECAP.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
– 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.
FEN IntroJava2006 AAU1 GUI: Graphical User Interface AWT/SWING: Components Drag and Drop in NetBeans Events Listeners.
1 Graphical User Interfaces AWT and Swing packages Frames and Panels Components Nested Panels Images Reading for this Lecture: L&L, 3.9 – 3.11.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
MIT-AITI 2004 – Lecture 16 Introduction to Swing.
Introduction to GUI Programming with Java Graphical User Interfaces With AWT and Swing Towson University *Ref:
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
GUI Basics. What is GUI? A graphical user interface (GUI) is a type of user interface item that allows people to interact with programs in more ways than.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
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.
COSC 3461: Module 2 Control Flow Paradigms: Reacting to the User.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Object Oriented Programming.  Interface  Event Handling.
Chapter 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 12 l Event-Driven Programming and GUIs l Swing Basics and.
Ch13 Creating windows and applets. Short overview AWT (Abstract Windowing Toolkit) Early Java development used graphic classesEarly Java development used.
COMP 150: Introduction to Object-Oriented Programming 1 Lecturer: Dr. AJ Bieszczad l Event-Driven Programming and GUIs l Swing Basics and a Simple Demo.
GUI Basics. Agenda What GUI How to make in java Creating frames Frequently used GUI components Layout Managers.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Basics of GUI Programming Chapter 11 and Chapter 22.
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
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)
Lesson 33: Layout management and drawing – Java GUI.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Event Driven (Asynchronous) Programming. Event handling in Unity Subclass a class that contains event handling methods, and then override those methods.
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:
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
A First Look at GUI Applications
A Quick Java Swing Tutorial
GUI Programming III: Events
Introduction to Computing Using Java
Window Interfaces Using Swing Objects Chapter 12
Steps to Creating a GUI Interface
A Quick Java Swing Tutorial
Presentation transcript:

Unit 101 Java GUI Components and Events  GUI Components and Containers  Adding Components to Containers  GUI Events  GUI Events Classes  Learning Outcomes oDistinguish between GUI components and containers. oIdentify and distinguish top-level containers from other containers. oWrite simple programs to add components into containers. oExplain what Events are, and distinguish between Event sources, Event classes and Event listeners.

Unit 102 Introduction to Components A component is an object having a graphical representation that can be displayed on the screen. Example of components in a typical GUI include: buttons, text boxes, lables and pop-up menus

Unit 103 Introduction to Containers  A container is a special component that can hold other components. Example of containers in typical GUI applications include: opanels, windows, applets, frames Functionality of most GUI components derive from the Component and Container classes.

Unit 104 Anatomy of Top-level Containers Each top-level container has only one component, JRootPane. The root pane consists of three other containers: the layered, content and glass panes:

Unit 105 Anatomy of Top-level Containers (cont’d) The root pane has a glass pane on top and a layered pane underneath. The glass pane component is always painted last and appears on top of the content pane and menu bar. The layered pane consists of a menu bar and a content pane. A content pane is a Container that covers the visible area of a container. A content pane is automatically created for a newly created container. Components must be added to the content pane of a container. The content pane can be retrieved using the getContentPane method.

Unit 106 Anatomy of an Application GUI JPanel JButton JFrame JLabel GUI Internal structure JFrame JPanel JButtonJLabel containers

Unit 107 Frames Frame is a window that is not contained inside another window. Frame is the basis to contain other user interface components in Java GUI applications. The Frame class can be used to create windows. For Swing GUI programs, use JFrame class to create widows. import javax.swing.*; public class MyFrame { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(400, 300); frame.setVisible(true); // Add a button into the frame frame.getContentPane().add(new JButton("OK")); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); }

Unit 108 NOTE The content pane is a subclass of Container. The statement in the preceding slide can be replaced by the following two lines: Container container = frame.getContentPane(); container.add(new JButton("OK")); You may wonder how a Container object is created. It is created when a JFrame object is created. A JFrame object uses the content pane to hold components in the frame.

Unit 109 Centering Frames By default, a frame is displayed in the upper-left corner of the screen. To display a frame at a specified location, you can use the setLocation(x, y) method in the JFrame class. This method places the upper-left corner of a frame at location (x, y).

Unit 1010 Your First Swing Program Import Swing package –Import javax.swing.*; –java.awt.* and java.awt.event.* At least one top-level container –JFrame, JDialog, JApplet –JFrame frame = new JFrame(“HelloWorld”); –setVisible(true); pack(); Create Swing components and add to content pane of frame –JLabel label = new JLabel(“Hello World”); –frame.getContentPane().add(label);

Unit 1011 Your First Swing Program import javax.swing.*; public class HelloWorld extends JFrame { public HelloWorld() { JLabel label = new JLabel("HelloWorld!"); // add component to frame’s container getContentPane().add(label); // make frame visible setVisible(true); // resize if necessary pack(); } public static void main(String[] args) { // create the frame HelloWorld frame = new HelloWorld(); }

Unit 1012 Example 1: Very Simple Swing Demonstration import javax.swing.*; import java.awt.*; // not always necessary, but often included public class FirstSwingDemo { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static void main(String[] args) { JFrame myWindow = new JFrame(); myWindow.setSize(WIDTH, HEIGHT); JLabel myLabel = new JLabel(“Please don’t click that button!”); myWindow.getContentPane().add(myLabel); WindowDestroyer myListener = new WindowDestroyer(); myWindow.addWindowListener(myListener); myWindow.setVisible(true); }

Unit 1013 Notes on the Simple Demo Program import javax.swing.*; public class FirstSwingDemo { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static void main(String[] args) { JFrame myWindow = new JFrame(); myWindow.setSize(WIDTH, HEIGHT); JLabel myLabel = new JLabel(“Please don’t click…”); myWindow.getContentPane().add(myLabel); WindowDestroyer myListener = new WindowDestroyer(); myWindow.addWindowListener(myListener); myWindow.setVisible(true); } Used in all Swing programs Creates a JFrame window named myWindow Adds a label to the JFrame window—note use of getContentPane

Unit 1014 Notes on the Simple Demo Program import javax.swing.*; public class FirstSwingDemo { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static void main(String[] args) { JFrame myWindow = new JFrame(); myWindow.setSize(WIDTH, HEIGHT); JLabel myLabel = new JLabel(“Please don’t click…”); myWindow.getContentPane().add(myLabel); WindowDestroyer myListener = new WindowDestroyer(); myWindow.addWindowListener(myListener); myWindow.setVisible(true); } Allows the program to respond to the event of a user clicking in the close box. WindowDestroyer is a programmer- defined class.

Unit 1015 The Window Destroyer Class public class WindowDestroyer extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } WindowAdapter is a class that includes all the methods required for window events. When a window closing event occurs, this method will be called and the program will quit.

Unit 1016 The Results of the Simple Demo Program import javax.swing.*; public class FirstSwingDemo { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static void main(String[] args) { JFrame myWindow = new JFrame(); myWindow.setSize(WIDTH, HEIGHT); JLabel myLabel = new JLabel(“Please don’t click…”); myWindow.getContentPane().add(myLabel); WindowDestroyer myListener = new WindowDestroyer(); myWindow.addWindowListener(myListener); myWindow.setVisible(true); } The window will not show up on the screen without a line like this one.

Unit 1017 Example 2: Creating Windows & Frames 1 import java.awt.*; import javax.swing.*; 2 public class TopLevelWindows{ 3 public static void main(String [] args){ 4 JFrame frame = new JFrame("My JFrame"); 5 frame.setLocation(100,100); 6 frame.setSize(300,300); 7 Container fcp = frame.getContentPane(); 8 JButton fb = new JButton("Draggable, Resizable Frame"); 9 fcp.add(fb); JWindow window = new JWindow(); 12 window.setLocation(500,100); 13 window.setSize(300,300); 14 Container wcp = window.getContentPane(); 15 JButton wb = new JButton("Unmovable, No Frills Window"); 16 wcp.add(wb); frame.setVisible(true); 19 window.setVisible(true); 20 } 21 }

Unit 1018 Example 3: Adding Components to Containers 1 import java.awt.*; 2 import javax.swing.*; 3 public class AddingComponents extends JFrame{ 4 5 JButton button = new JButton("Press Me"); 6 JLabel label = new JLabel( "Running Total:"); 7 JTextField textField = new JTextField(10); 8 Container cp = getContentPane(); 9 10 public AddingComponents() { 11 super("A Container With Components"); 12 setSize(300,100); 13 cp.setLayout(new FlowLayout()); 14 cp.add(label); 15 cp.add(textField); 16 cp.add (button); 17 setVisible(true); 18 } 19 public static void main(String args []) { 20 new AddingComponents(); 21 } 22 }

Unit 1019 Introduction to GUI Events We will now discuss how components and containers communicate. When a user interacts with a GUI component, events are triggered. An event is an action triggered by the user or by some other means. For example, we may want our program to perform some action when the following occurs: –The mouse is moved –A mouse button is clicked –The mouse is dragged –A graphical button is clicked –A keyboard key is pressed –A timer expires When an event is triggered an event object is created and delivered to the event receivers. Execution of these kinds of programs is driven by users’ activation of events. Event classes, event sources and event listeners are three groups of Java classes crucial for event-driven programming.

Unit 1020 Events and Listeners Generator This object may generate an event Listener This object waits for and responds to an event Event When an event occurs, the generator calls the appropriate method of the listener, passing an object that describes the event. The Java standard class library contains several classes that represent typical events Certain objects, such as an applet or a graphical button, generate (fire) an event when it occurs Other objects, called listeners, respond to events We can write listener objects to do whatever we want when an event occurs

Unit 1021 Listener Interfaces We can create a listener object by writing a class that implements a particular listener interface. The Java standard class library contains several interfaces that correspond to particular event categories. The MouseListener interface contains methods that correspond to mouse events After creating the listener, we add the listener to the component that might generate the event to set up a formal relationship between the generator and listener. The following are called key events: –key pressed: a keyboard key is pressed down –key released: a keyboard key is released –key typed: a keyboard key is pressed and released The KeyListener interface handles key events Listener classes are often implemented as inner classes, nested within the component that they are listening to.

Unit 1022 Mouse Events The following are mouse events: –mouse pressed: the mouse button is pressed down –mouse released: the mouse button is released –mouse clicked: the mouse button is pressed and released –mouse entered: the mouse pointer is moved over a particular component –mouse exited: the mouse pointer is moved off of a particular component The following are called mouse motion events: –mouse moved: the mouse is moved –mouse dragged: the mouse is moved while the mouse button is held down There is a corresponding MouseMotionListener interface One class can serve as both a generator and a listener One class can serve as a listener for multiple event types

Unit 1023 Events Classes Hierarchy Event classes represent events and contain methods for getting information on the events. Here is the class hierarchy for events classes:

Unit 1024 Events Source Classes An event source is the component that generates an event. A source must register listeners who may wish to take some action when the event is generated. When an event occurs the source informs all registered listeners for this event. An event listener can register or un-register with the following methods: 1. public void addTypeListener(TypeListener t) button.addActionListener(new ActionListener(); 2. public void removeTypeListener (TypeListener t) button.removeActionListener(new ActionListener(); Type is the name of the event and t is a reference to the event listener.

Unit 1025 Events Listener Classes The java.awt.event package contains interfaces and classes for dealing with events. Each listener interface is a specification for receiving a particular type of event. An event listener class implements the listener interfaces of interest to the class. Every event handler should satisfy these two conditions: 1. Implement an interface. 2. Register as event listener.

Unit 1026 Types of Listeners ActionListener KeyListener, MouseListener, MouseMotionListener, TextListener AdjustmentListener, ComponentListener, ContainerListener, FocusListener, WindowListener Listeners are Interfaces.

Unit 1027 Events: A Pictorial View

Unit 1028 Mohamed ICS Student Data EntryForm

Unit 1029 import java.awt.*; public class EntryForm { private Frame frame; private Button enterBtn; private TextField nameTxf; private TextField majorTxf; private TextField gpaTxf; private TextField creditsTxf; // constructor public EntryForm () { Student Data EntryForm

Unit 1030 // create components frame = new Frame ("Student Data Entry Form"); nameTxf = new TextField (20); majorTxf = new TextField (20); gpaTxf = new TextField (3); creditsTxf = new TextField (3); enterBtn = new Button ("Enter"); // add components to frame frame.setLayout (new FlowLayout()); frame.add (new Label ("Name")); frame.add (nameTxf); frame.add (new Label ("Major")); Student Data EntryForm

Unit 1031 frame.add (majorTxf); frame.add (new Label ("GPA")); frame.add (gpaTxf); frame.add (new Label ("Credits")); frame.add (creditsTxf); frame.add (enterBtn); // show frame frame.pack(); frame.setVisible (true); } // end of constructor } // end of class public class EntryFormApp { // main program public static void main (String[] args) { new EntryForm(); }} Student Data EntryForm

Unit 1032 Exercises 1.The Panel, Window and JComponent class each subclasses Component class. Write down the similarities and differences between these classes in a tabular form. 2.Write down in tabular form the similarities and differences between top-level components and other GUI components. 3.Write a Java program to display three frames as follows. The top-left corner of the second frame should have the same coordinates as the bottom-right corner of the first frame. Similarly, the top-left corner of the third frame should have the same coordinates as the bottom-right corner of the second frame. 4.Run the program in Example 2. Try resizing the window and watch how the components placements change. Modify this program by adding four more buttons. Remove the setSize method call and replace it with the call to the pack method. Re-run the program and notice the output. 5.Write short notes on a. Event classes b. Event sources c. Event listeners