Java AWT Windows, Text, & Graphics

Similar documents
Module 4 Multi threaded Programming, Event Handling. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

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

Programming Mobile Devices J2SE GUI

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

Advanced Java Programming (17625) Event Handling. 20 Marks

SD Module-1 Advanced JAVA

SD Module-1 Advanced JAVA. Assignment No. 4

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

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

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

The AWT Event Model 9

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

GUI in Java TalentHome Solutions

GUI Programming: Swing and Event Handling

Interacción con GUIs

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

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

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...

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

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

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali

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

Mobile MOUSe JAVA2 FOR PROGRAMMERS ONLINE COURSE OUTLINE

G51PRG: Introduction to Programming Second semester Applets and graphics

BM214E Object Oriented Programming Lecture 13

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

Introduction to the JAVA UI classes Advanced HCI IAT351

Packages: Putting Classes Together

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

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

Sri Vidya College of Engineering & Technology

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

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

COMPSCI 230. Software Design and Construction. Swing

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

CS 251 Intermediate Programming GUIs: Event Listeners

Dr. Hikmat A. M. AbdelJaber

GUI Event Handlers (Part I)

Window Interfaces Using Swing Objects

Java Control Fundamentals

The Abstract Window Toolkit

Graphical Interfaces

Graphical Interfaces

CHAPTER 2. Java Overview

Graphical User Interfaces. Comp 152

Java. GUI building with the AWT

BASICS OF GRAPHICAL APPS

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

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

12/22/11. Copyright by Pearson Education, Inc. All Rights Reserved.

Window Interfaces Using Swing Objects

Event Driven Programming

Assignment No 2. Year: Dept.: ComputerTech. Sanjivani Rural Education Society s Sanjivani KBP Polytechnic, Kopargaon

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

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

Unit - 2 Abstract Window Toolkit

Chapter 1 GUI Applications

Basicsof. JavaGUI and SWING

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).

CSC207H: Software Design Lecture 11

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!

Chapter 6: Graphical User Interfaces

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

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

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

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

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

Handling Mouse and Keyboard Events

AWT WINDOW CLASS. The class Window is a top level window with no border and no menubar. It uses BorderLayout as default layout manager.

Graphical User Interfaces in Java - SWING

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

Computer Programming Java AWT Lab 18

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

This exam is closed textbook(s) and closed notes. Use of any electronic device (e.g., for computing and/or communicating) is NOT permitted.

AWT CHOICE CLASS. Choice control is used to show pop up menu of choices. Selected choice is shown on the top of the menu.

Java Applets / Flash

Programming Languages and Techniques (CIS120e)

CS 251 Intermediate Programming GUIs: Components and Layout

Programming graphics

AWT CHECKBOX CLASS. Creates a check box with the specified label and sets the specified state.

Jonathan Aldrich Charlie Garrod

Overloading Example. Overloading. When to Overload. Overloading Example (cont'd) (class Point continued.)

JAVA PROGRAMMING COURSE NO. IT-705(A) SECTION - A

7. Program Frameworks

CS11 Java. Fall Lecture 4

UNIT - 6 AWT SWINGS [ABSTARCT WINDOW TOOLKIT]

Java: Graphical User Interfaces (GUI)

JAVA. Object Oriented Programming with. M.T. Somashekara D.S.Guru K.S. Manjunatha

CS11 Java. Fall Lecture 3

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

Programming Language Concepts: Lecture 8

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

Graphical User Interface (GUI)

The AWT Package, An Overview

AWT LIST CLASS. The List represents a list of text items. The list can be configured to that user can choose either one item or multiple items.

Swing from A to Z Some Simple Components. Preface

Graphic User Interfaces. - GUI concepts - Swing - AWT

Transcription:

2 AWT Java AWT Windows, Text, & Graphics The Abstract Windows Toolkit (AWT) contains numerous classes and methods that allow you to create and manage applet windows and standard windows that run in a GUI environment, such as Windows The AWT classes are contained in the java.awt package. 3 4 Window Fundamentals AWT class Hierarchy The AWT defines windows based on a class hierarchy that adds functionality at each level. The two most common windows are those derived from Panel used by applets and Frame that creates standard windows. 5 6 AWT class Hierarchy Component is an abstract class that encapsulates all all of the user interface elements that are displayed on the screen and that interact with the user. The container class is an abstract subclass of Component. The class is responsible for laying out any components it contains through using various layout managers. AWT class Hierarchy The Panel class is a concrete subclass of Container. When screen output is directed to an applet, it is drawn on the surface of a Panel object. In essence, a Panel is a window that does not contain a title bar, menu bar, or border.

7 8 AWT class Hierarchy Frame encapsulates what is commonly thought of as a window. It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. When a Frame window is created from within an applet window, warning message will produced. When a Frame window is created by a program, a normal window is created. Frame Windows Frame supports two constructors: Frame() & Frame(String title) You cannot specify the dimensions of the window. Instead, you must set the size after the window has been created by using the following two methods: void resize(int newwidth, int newheight) void resize(dimension newsize) 9 10 Frame Windows Once a Frame window is created, it will not be visible until you call show(). To hide a window, call hide(). To set new title, use settitle(string newtitle). import java.awt.*; public class BoringFrame1 { Using Class Frame Create a new JFrame public static void main(string[] args) { Frame test = new Frame("A Boring Frame"); Set its dimensions test.setsize(300,200); Set its position test.setlocation(100,200); test.setbackground(color.white); test.show(); Set its background colour Make it visible on the screen 11 12 import java.awt.*; public class BoringFrame2 extends Frame { public BoringFrame2() { super( Ishbel"); this.setsize(400,100); this.setlocation(100,200); this.setbackground(color.cyan); this.setvisible(true); public static void main(string[] args) { BoringFrame2 test = new BoringFrame2(); Another Frame Eventi Evento: qualcosa che l utente fa sulla interfaccia grafica Cliccare su un pulsante, scrivere in un campo. Ogni evento coinvolge tre oggetti La sorgente, ossia l oggetto che ha causato l evento (es. il pulsante cliccato) L evento, anch esso rappresentato come un oggetto (es. ActionEvent, clic di un pulsante) Il listener, ossia l oggetto che deve rispondere all evento

13 14 Oggetto listener Per gestire gli eventi è necessario implementare un listener Esempio: public class MyApplication implements ActionListener { Gestire gli eventi Il listener deve trattare il messaggio actionperformed public void actionperformed(actionevent ae) La sorgente (controllo gui) deve sapere quale oggetto gestirà gli eventi da essa prodotti (listener) calcbutton.addactionlistener(this); Metodo actionperformed public void actionperformed(actionevent event) { String name = namefield.gettext(); int rate = Integer.parseInt(rateField.getText()); Employee e = new Employee(name, rate); int hours = Integer.parseInt(hoursField.getText()); int pay = e.calcpay(hours); String result = e.getname().concat(" earned $"). concat(integer.tostring(pay)); resultlabel.settext(result); dolayout(); 15 import java.awt.*; import java.awt.event.windowevent; import java.awt.event.windowlistener; public class BoringFrame3 implements WindowListener { private Frame test; Evento WindowClosing public BoringFrame3() { test = new Frame("Closeable Frame"); test.setsize(300,200); test.setlocation(100,200); test.setbackground(color.white); test.show(); test.addwindowlistener(this); public static void main(string[] args) { BoringFrame3 app = new BoringFrame3(); public void windowclosing(windowevent we) { test.hide(); System.exit(0); 16 18 Controls Java AWT Controls Layout Managers Menus The AWT supports the following types of control subclasses of Component: Labels Buttons Check boxes Check box groups Drop-down menus Lists Scroll bars Text editing

19 20 Controls & Events Except for labels, all other controls generate events. To handle control-generated events, your program must implements the related listener interface. ActionListener AdjustmentListener AWTEventListener ComponentListener ContainerListener FocusListener HierarchyBoundsListener HierarchyListener InputMethodListener ItemListener KeyListener MouseListener MouseMotionListener MouseWheelListener TextListener WindowFocusListener WindowListener WindowStateListener Listener Interfaces The listener interface for receiving action events. The listener interface for receiving adjustment events. The listener interface for receiving notification of events dispatched to objects that are instances of Component or MenuComponent or their subclasses. The listener interface for receiving component events. The listener interface for receiving container events. The listener interface for receiving keyboard focus events on a component. The listener interface for receiving ancestor moved and resized events. The listener interface for receiving hierarchy changed events. The listener interface for receiving input method events. The listener interface for receiving item events. The listener interface for receiving keyboard events (keystrokes). The listener interface for receiving "interesting" mouse events (press, release, click, enter, and exit) on a component. The listener interface for receiving mouse motion events on a component. The listener interface for receiving mouse wheel events on a component. The listener interface for receiving text events. The listener interface for receiving WindowEvents, including WINDOW_GAINED_FOCUS and WINDOW_LOST_FOCUS events. The listener interface for receiving window events. The listener interface for receiving window state events. 21 22 Events Controls & Events ActionEvent AdjustmentEvent AWTEventListenerPro xy ComponentEvent ContainerAdapter ContainerEvent FocusEvent HierarchyBoundsAdap ter HierarchyEvent InputEvent InputMethodEvent InvocationEvent ItemEvent KeyEvent MouseEvent MouseWheelEvent PaintEvent TextEvent WindowEvent A semantic event which indicates that a component-defined action occured. The adjustment event emitted by Adjustable objects. A class which extends the EventListenerProxy, specifically for adding an AWTEventListener for a specific event mask. A low-level event which indicates that a component moved, changed size, or changed visibility (also, the root class for the other component-level events). An abstract adapter class for receiving container events. A low-level event which indicates that a container's contents changed because a component was added or removed. A low-level event which indicates that a Component has gained or lost the input focus. An abstract adapter class for receiving ancestor moved and resized events. An event which indicates a change to the Component hierarchy to which a Component belongs. The root event class for all component-level input events. Input method events contain information about text that is beingcomposed using an input method. An event which executes the run() method on a Runnablewhen dispatched by the AWT event dispatcher thread. A semantic event which indicates that an item was selected or deselected. An event which indicates that a keystroke occurred in a component. An event which indicates that a mouse action occurred in a component. An event which indicates that the mouse wheel was rotated in a component. The component-level paint event. A semantic event which indicates that an object's text changed. A low-level event that indicates that a window has changed its status. The Event class defines several fields and constants for event handling. The two most important fields are source, which contains a reference to the object that generates the event, and id, which contains the constant that identifies the event. Other event specific information are available. 23 24 Labels Label contains a string which it displays. Label defines 3 constructors: Label() Label(String str) Label(String str, int alignment) The string in a label can be changed by settext() and abstracted by gettext(). Buttons A button contains a label and generates an event when it is pressed. A button can created by: Button() or Button(String labelstr) or Button listname[] = new Button[#ofelement] The label string can be changed by setlabel() and retrieved by getlabel().

25 26 Check Boxes Check Boxes A check box is associated with a label and a state of either checked or unchecked. Check boxes are objects of the Checkbox class and can be created by: Checkbox() Checkbox(String labelstr) Checkbox(String labelstr, CheckboxGroup groupname, boolean on) Use getstate() to retrieve the current state of a check box and setstate() to set its state. Use getlabel() to retrieve the current label and setlabel() to set the label. 27 28 Check Box Group The CheckboxGroup contains a set of mutually exclusive check boxes which are often called ratio buttons. CheckboxGroup() Checkbox(labelName, groupname, boolean on) The getcurrent() method returns the check box being checked and the setcurrent() method sets a check box. Choice The Choice class creates a pop-up list of items. Each item is a string that appears as a left-justified label in the order it is added. Choice only defines the default constructor, which creates an empty line. To add an item, use additem(): additem(string name) 29 30 Choice Choice To retrieve the item being currently selected, use String getselecteditem() or int getselectindex(). To obtain the number of items in the list, use int countitems(). To set a selected item, use void select(int index) or void select(string name) To retrieve the name of an item at an index, use String getitem(int index)

31 32 List List The List class provides a compact, multiple-choice, scrolling selection list. List provides two constructors: List() List(int numrows, boolean multipleselect) To add a selection, use additem(). List selections are to be double-clicked. For lists with only one selection, current item selected can be retrieved by using String getselecteditem() or int getselectedindex() For lists with multiple selections, use String[] getselecteditems() or int[] getselectedindexes() 33 34 TextField The TextField class implements a single-line text-entry area that allowss the user to enter strings, edit the string using the arrow keys, cut and paste keys, and mouse selections TextField has four constructors: TextField() TextField(int numchars) TextField(String str) TextField(String str, int numchars) TextField Use gettext() to get current string store in the text field; use settext() to set the the text. To retrieve a portion of the text, use void select(int startindex, int endindex) To control the modifiability of the text field, use seteditable(). 35 36 Containers A Container is a GUI elements that hold other components (containers and controls) Each Container object has a layout manager associated with it. Layout Manager A layout manager is an object responsible of GUI components disposition A layout manager is an instance of any class that implements the LayoutManager interface. The layout manager is set by the setlayout() method. If no call is made to setlayout() is made, the default layout manager is used.

37 38 Layout Manager Whenever a container is resized, the layout manager is used to position each of the components within it. Each layout manager keeps track of a list of components that are stored by their names. The layout manager automatically rearranges the layout of its components. Layout Manager FlowLayout BorderLayout GridLayout CardLayout GridBagLayout 39 40 FlowLayout BorderLayout 41 42 GridLayout CardLayout colonne righe

43 44 GridBagLayout Riferimenti La documentazione java Packages: java.awt java.awt.event