Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Similar documents
The AWT Event Model 9

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Dr. Hikmat A. M. AbdelJaber

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

Graphical Interfaces

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

Graphical Interfaces

Programming Languages and Techniques (CIS120e)

Graphical User Interfaces in Java - SWING

Window Interfaces Using Swing Objects

SD Module-1 Advanced JAVA

Interacción con GUIs

SD Module-1 Advanced JAVA. Assignment No. 4

Systems Programming Graphical User Interfaces

BM214E Object Oriented Programming Lecture 13

Chapter 1 GUI Applications

Packages: Putting Classes Together

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI

Programming Mobile Devices J2SE GUI

Introduction to the JAVA UI classes Advanced HCI IAT351

GUI in Java TalentHome Solutions

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

Graphical User Interfaces (GUIs)

Swing from A to Z Some Simple Components. Preface

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

Window Interfaces Using Swing Objects

GUI Design. Overview of Part 1 of the Course. Overview of Java GUI Programming

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Lecture 5: Java Graphics

GUI Programming: Swing and Event Handling

Basicsof. JavaGUI and SWING

Advanced Java Programming (17625) Event Handling. 20 Marks

Java. GUI building with the AWT

PIC 20A GUI with swing

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

กล ม API ท ใช. Programming Graphical User Interface (GUI) Containers and Components 22/05/60

Graphic User Interfaces. - GUI concepts - Swing - AWT

Programming Language Concepts: Lecture 8

COMPSCI 230. Software Design and Construction. Swing

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Event Driven Programming

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

MIT AITI Swing Event Model Lecture 17

G51PRG: Introduction to Programming Second semester Applets and graphics

Java GUI Design: the Basics

CS 251 Intermediate Programming GUIs: Event Listeners

CSE 331. Event- driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Java Programming Lecture 6

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

14.2 Java s New Nimbus Look-and-Feel 551 Sample GUI: The SwingSet3 Demo Application As an example of a GUI, consider Fig. 14.1, which shows the SwingS

GUI Event Handling 11. GUI Event Handling. Objectives. What is an Event? Hierarchical Model (JDK1.0) Delegation Model (JDK1.1)

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

AP CS Unit 11: Graphics and Events

Agenda. Container and Component

CS11 Java. Fall Lecture 4

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

Java: Graphical User Interfaces (GUI)

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

Java - Applications. The following code sets up an application with a drop down menu, as yet the menu does not do anything.

Lecture 3: Java Graphics & Events

Together, the appearance and how user interacts with the program are known as the program look and feel.

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan

BASICS OF GRAPHICAL APPS

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation

Chapter 8. Java continued. CS Hugh Anderson s notes. Page number: 264 ALERT. MCQ test next week. This time. This place.

Java continued. Chapter 8 ALERT ALERT. Last week. MCQ test next week. This time. This place. Closed book. Assignment #2 is for groups of 3

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

Java AWT Windows, Text, & Graphics

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

User interfaces and Swing

(Incomplete) History of GUIs

Chapter 6: Graphical User Interfaces

Course: CMPT 101/104 E.100 Thursday, November 23, 2000

OBJECT ORIENTED PROGRAMMING. Java GUI part 1 Loredana STANCIU Room B616

CS11 Java. Fall Lecture 3

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

SampleApp.java. Page 1

Jonathan Aldrich Charlie Garrod

Part 3: Graphical User Interface (GUI) & Java Applets

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Graphical User Interfaces. Comp 152

Building Java Programs Bonus Slides

1005ICT Object Oriented Programming Lecture Notes

Swing from A to Z Using Focus in Swing, Part 2. Preface

Transcription:

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing Rui Moreira Some useful links: http://java.sun.com/docs/books/tutorial/uiswing/toc.html http://www.unix.org.ua/orelly/java-ent/jfc/ Graphical User Interfaces n Java provides a good integration with interactive web-based applications - Applets, JSP, Servlets n The Java Foundation Classes (JFC) include packages (cf. AWT & Swing J2SE) with built-in components and functionality for assembling GUIs n Both packages provide mechanisms for building GUI interfaces (e.g., windows, buttons, text fields, etc.) Rui Moreira 2 1

AWT vs Swing n No big architecture differences between AWT and Swing since both define an euivalent class hierarchy, but using different packages, e.g.: java.awt.frame javax.swing.jframe java.awt.panel javax.swing.jpanel java.awt.dialog javax.swing.jdialog java.awt.button javax.swing.jbutton java.awt.textfield javax.swing.jtextfield java.awt.label javax.swing.jlabel java.awt.checkbox javax.swing.jcheckbox java.awt.combobox javax.swing.jcombobox java.awt.list java.swing.jlist n Major difference is related with rendering (how components are drawn/displayed on screen) n We cannot use/combine components from both packages in the same GUI (container) although they share Layout Managers Rui Moreira 3 AWT n The first Java package (java.awt) for building GUI components was AWT (Abstract Window Toolkit) - JDK 1.0 & JDK 1.1. n Graphical components look different in different Operating System (OS) n Defines/uses heavy-weight components each owning its own viewport which sends output info (via OS) to the screen n Each component has less code (than counterpart Swing) because it uses a peer component (Native Screen Source) provided by the OS which renders the component to screen Rui Moreira 4 2

Swing n Since J2SE (JDK1.2) Java includes a new package (javax.swing) which is a pure Java release n Graphical components look the same in different Operating System (OS) n Defines/uses light-weight components each redirects drawing to the component it build on n Each component has more code (than counterpart AWT) because it provides a richer and OS-independent functionality natively implemented in the component n All components use the same OS peer component for rendering Rui Moreira 5 Major elements n GUI Components (e.g., Button, Label, TextField) Graphical elements responsible for the interaction and that may live inside containers n Containers (e.g., Frame, Panel, Dialog) Components that group/assemble several graphical elements or even other containers n Layout Managers (e.g., FlowLayout, BorderLayout, GridLayout) Elements responsible for managing/structuring the way components are added/organized inside a container n Events (e.g., ActionEvent, MouseEvent, WindowEvent) Objects that describe an action performed by the user on interface elements n Listeners/Handlers (e.g., ActionListener, MouseListener) Elements responsible for detecting/receiving interaction events and select/execute associated action code Rui Moreira 6 3

GUI Components n There are several graphical elements/components that may be instantiated and added to a container to be displayed on screen: // Using AWT Button b = new Button( Ok ); Label l = new Label( Press ok ); TextBox t = new TextBox(); // Using Swing JButton jb = new JButton( Ok ); JLabel jl = new JLabel( Press ok ); JTextBox jt = new JTextBox(20); Rui Moreira 7 Containers n There are several types of containers which are used to group together several GUI components n Each container may include several GUI components and may also include other inner containers (to mix together different layouts) // Using AWT Frame f = new Frame( AWT Frame Example ); Panel p = new Panel(); // Using Swing JFrame jf = new JFrame( Swing Frame Example ); JPanel jp = new JPanel(); Rui Moreira 8 4

AWT GUI Components hierarchy Legend: Rui Moreira 9 Swing hierarchy Legend: Rui Moreira 10 5

Add Component to Container import java.awt.container; import javax.swing.*; /** TestButton: class for testing a Button inside Frame */ public class TestButton { public static void void main(string args[]){ // CREATE JFrame (container) & JButton (component) JFrame jf = new JFrame( Frame Test button ); JButton jb = new JButton( Ok ); // GET Container reference to ADD JButton Container c = g.getcontentpane(); c.add( Center, b); // Pack and Show f.pack(); f.setvisible(true) //Deprecated: f.show(); Rui Moreira 11 Layout Managers n Layout Managers are responsible for adding/organizing GUI elements inside containers n Layout Managers control the position and size of each GUI component inside the container n Each container has a reference to its Layout Manager and whenever we add a GUI component to the container it invokes the respective Layout Manager to do it (deciding the size and position of the component to be added) n Each container has a default Layout Manager (that we may change) Rui Moreira 12 6

AWT Layout Managers n FlowLayout: positions GUI components in lines (centered) like words in a text page (default for Panel and Applet) n BorderLayout: positions GUI components on 5 different predefined areas - North, South, West, East and Center (default for Frame, Window and Dialog) n CardLayout: organizes interfaces like layers; we may only see a layer/card at a time n GridLayout: positions GUI components over a pre-defined grid/matrix; number of lines & columns are specified by developer n GridBagLayout: positions GUI components over a pre-defined grid/matrix but columns may have different sizes and GUI components may overlap several columns Rui Moreira 13 Layout Managers hierarchy NB: Swing containers (e.g., JFrame, JPanel) use these AWT Layout Managers Rui Moreira 14 7

Set JFrame Layout import java.awt.flowlayout; import javax.swing.*; public class TestButton { public static void void main(string args[]){ // CREATE JFrame (container) & JButton (component) JFrame jf = new JFrame( Frame Test button ); JButton jb = new JButton( Ok ); // GET Container reference to ADD JButton Container c = g.getcontentpane(); // SET JFrame LAYOUT (by default is BorderLayout) c.setlayout(new FlowLayout()); c.add( Center, b); // Pack and Show f.pack(); f.setvisible(true) //Deprecated: f.show(); Rui Moreira 15 Events n When users act over GUI components one/several events may be triggered n Events are described by pre-defined classes/objects which characterize the event and its source component, e.g., ActionEvent: action events on buttons/menus, e.g., action performed MouseEvent: mouse events, e.g., moved, pressed, entered, etc. WindowEvent: window events, e.g., closing, iconified, etc. ItemEvent: list box events, e.g., item state changed TextEvent: text box events, e.g., text value changed Rui Moreira 16 8

AWT Events hierarchy NB: Swing components (e.g., JFrame, JButton, JTextField) also detect/delegate these events to listeners/handlers Rui Moreira 17 Swing Events hierarchy Legend: Rui Moreira 18 9

Listeners/Handlers n Java provides/implements a Delegation Event Model: each GUI component detects its own events - triggered by specific user-interactions (e.g., press button, move mouse, etc.) to detect these events developers must register specific eventlisteners with each GUI component GUI components then delegate/forward event handling to these pre-registered methods - handlers n Event Listeners are specific Java interfaces (e.g., ActionListener, MouseListener) that group/define methods for handling particular sets of events n Event-Handlers are classes (built by developers) that implement specific Event-Listeners, i.e., provide methods/behavior that will receive the event objects and act accordingly Rui Moreira 19 AWT Listeners hierarchy Rui Moreira 20 10

Swing Listeners hierarchy Rui Moreira 21 Implement an Event-Handler import java.awt.event.*; /** ButtonHandler: class that we implement for handling events related with buttons pressed */ public class ButtonHandler implements ActionListener { // The ActionListener interface defines only // the actionperformed() method public void actionperformed(actionevent ae){ JButton jb = (JButton )ae.getsource(); String sb = ae.getactioncommand(); // sb=jb.gettext(); // Just print out the button name System.out.println( Someone pressed button +sb); Rui Moreira 22 11

Register an Event-Handler import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TestButton { public static void void main(string args[]){ JFrame jf = new JFrame( Frame Test button ); JButton jb = new JButton( Ok ); // REGISTER event-handler with Button b.addactionlistener(new ButtonHandler()); // Add Button to Frame ( Center of BorderLayout) Container c = g.getcontentpane(); c.add( Center, b); f.pack(); f.setvisible(true) //Deprecated: f.show(); Rui Moreira 23 Listeners/Handlers n The Button class has a specific method - addactionlistener() - for registering an ActionListener Handler with the button n Buttons trigger/detect ActionEvents which are handled by a specific method - actionperformed() - defined in the ActionListener interface n Developers must implement specific ActionListener Handlers for dealing with the ActionEvents of each button Rui Moreira 24 12

Listeners/Handlers n Each GUI component provides specific methods for registering different types of Listeners/Handlers, e.g., addmouselistener() is provided by buttons for registering MouseListener Handlers; addwindowlistener() is provided by containers (e.g., Frame) for registering WindowListener Hanlders n Each event category is detected by specific listeners which define particular sets of methods for handling those events n Methods defined by Event Listener interfaces are intuitively named according to the handled events Rui Moreira 25 Examples of Events Categories Event Listener Methods ActionEvent ActionListener actionperformed() MouseEvent MouseMotionListener mousedragged(), mousemoved() MouseEvent MouseListener mousepressed(), mousereleased(), etc. WindowEvent WindowListener windowclosing(), windowopened(), etc. TextEvent TextListener textvaluechanged() ItemEvent ItemListener itemsatechanged() Rui Moreira 26 13

Adapters n For each Listener interface Java defines a correspondent Adapter, e.g., MouseListener interface MouseAdapter class ActionListener interface ActionAdapter class n Adapters are classes which implement Listener interfaces but with empty methods n Developers may use (via extends) Adapters to code event handlers without having to implement all the methods defined in Listener interfaces Rui Moreira 27 Delegation Model Advantages n The Delegation Model has some advantages in comparison with the hierarchical model previously used by JDK1.0: Events are no longer accidentally resolved (handled) by containers (in the hierarchical model events could propagate to upper-level containers and then unexpectedly handled by them) Developers my create several filter classes (Adapters) to classify/select event actions The delegation model is more suitable for distributing work among different event-handler classes The delegation model provides support for Java Beans Rui Moreira 28 14

Exercises n Implement the following GUIs: ColoredFrame: JFrame with 2 JButtons (blue, yellow) that change the background color of the frame; LoginFrame: JFrame with JLabels, JTextFields, JPasswordFields and JButtons to perform a login (just print out the content of the text and password fields); ChatFrame: JFrame with JTextArea, JTextField and JButton to implement the GUI of a chat room; detect/handle ActionEvent (detect send button action cut text field to text area) and KeyEvent (detect \n key pressed on the text field cut text field to text area) by implementing ActionListener and KeyListener; use reuestfocus() method to set the focus on the text field; MenuFrame: JFrame with a menu bar that has the following menus -File, Edit, Help; File menu has options - Save, Load and Quit; Selecting the Quit menu option triggers an ActionEvent that should exit the program; Calculator: GUI calculator for basic arithmetic operations (+, -, * and /); use 3 JPanels; North panel shows output JTextField; Center JPanel uses GridLayout with all number and operation JButtons; South panel shows clear JButton. Rui Moreira 29 CardLayout Example (1/5) public class CardLayoutFrame extends JFrame implements MouseListener, WindowListener, KeyListener { // Declare/Create JPanels, JLabels, JButtons and CardLayout JPanel jp1 = new JPanel(), jp2 = new JPanel(), jp3 = new JPanel(), jp4 = new JPanel(); JLabel jl1 = new JLabel( Panel 1 ), jl2 = new JLabel( Panel 2 ), jl3 = new JLabel( Panel 3 ), jl4 = new JLabel( Panel 4 ); JButton jb1 = new JButton( Go 2 ), jb1 = new JButton( Go 3 ), jb3 = new JButton( Go 4 ), jb1 = new JButton( Go 1 ); CardLayout cl = new CardLayout(); Container c = null; // Container will be set latter // To be continue... Rui Moreira 30 15

//... Continue (2/5) public class CardLayoutFrame extends JFrame implements MouseListener, WindowListener { // Implement Constructor public CardLayoutFrame (String frametitle){ super(frametitle); // Call Constructor of JFrame c = this.getcontentpane(); // Get JFrame Container c.setlayout(this.cl); // Set layout manager of JFrame Container // Add each JPanel to a Named-Card of the JFrame container c.add(this.jp1, First ); // 1st JPanel added to card named First c.add(this.jp1, Second ); // 2nd JPanel added to card named Second... // Add each JLabel and JButton to the respective JPanel this.jp1.add(this.jl1); this.jp1.add(this.jb1);... // Set Listener/Handler (himself) for each JButton this.jb1.addactionlistener(this);... this.cl.show(c, First ); // Show First Card of JFrame Container this.setsize(200, 200); // Set JFrame size this.setvisible(true); // Set JFrame visible // To be continue... Rui Moreira 31 //... Continue (3/5) public class CardLayoutFrame extends JFrame implements MouseListener, WindowListener { //... // Implementing MouseListener public void actionperformed(actionevent ae){ String str = ae.getactioncommand(); // Check/Select which Card to Show if (str.eualsignorecase( Go 2 )){ this.cl.show(this.c, Second ); else if (str.eualsignorecase( Go 3 )){ this.cl.show(this.c, Third );... else if (str.eualsignorecase( Go 1 )){ this.cl.show(this.c, First ); // To be continue... Rui Moreira 32 16

//... Continue (4/5) public class CardLayoutFrame extends JFrame implements MouseListener, WindowListener { // Implementing WindowListener public void windowactivated(windowevent e) { public void windowclosed(windowevent e) { // Implement only the Close button of JFrame - Exit public void windowclosing(windowevent e) { this.c.dispose(); // Dispose JFrame System.exit(0); // Exit Application public void windowdeactivated(windowevent e) { public void windowdeiconified(windowevent e) { public void windowiconified(windowevent e) { public void windowopened(windowevent e) { // To be continue... Rui Moreira 33 //... Continue (5/5) public class CardLayoutFrame extends JFrame implements MouseListener, WindowListener { //... // Run Application public static void main(string args[]){ CardLayoutFrame cf = new CardLayoutFrame( Test CardLayout ); cf.setsize(200, 200); cf.setvisible(true); // The End Rui Moreira 34 17