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

Similar documents
Chapter 1 GUI Applications

UNIT-V. There are two sets of Java APIs for graphics programming: AWT (Abstract Windowing Toolkit) and Swing.

GUI in Java TalentHome Solutions

Graphical Interfaces

Graphical Interfaces

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

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

The AWT Event Model 9

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

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

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

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

SD Module-1 Advanced JAVA

SD Module-1 Advanced JAVA. Assignment No. 4

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

Programming Mobile Devices J2SE GUI

BM214E Object Oriented Programming Lecture 13

Window Interfaces Using Swing Objects

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

Advanced Java Programming (17625) Event Handling. 20 Marks

Programming Languages and Techniques (CIS120e)

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

GUI Programming: Swing and Event Handling

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

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

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

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

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!

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

Window Interfaces Using Swing Objects

Java. GUI building with the AWT

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

Swing from A to Z Some Simple Components. Preface

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

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

User interfaces and Swing

Programming graphics

AWT TEXTFIELD CLASS. Constructs a new empty text field with the specified number of columns.

Introduction to the JAVA UI classes Advanced HCI IAT351

IS311 Programming Concepts. GUI Building with Swing

Agenda. GUI Building with Swing ต องม พ นความร ต อไปน ก อน. Java Graphical User Interfaces. IS311 Programming Concepts

Packages: Putting Classes Together

Unit 7: Event driven programming

CHAPTER 2. Java Overview

Cheng, CSE870. More Frameworks. Overview. Recap on OOP. Acknowledgements:

Systems Programming Graphical User Interfaces

Java AWT Windows, Text, & Graphics

GUI Event Handlers (Part I)

Graphical User Interfaces. Comp 152

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

Sri Vidya College of Engineering & Technology

AWT DIALOG CLASS. Dialog control represents a top-level window with a title and a border used to take some form of input from the user.

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

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

University of Cape Town ~ Department of Computer Science. Computer Science 1016S / 1011H ~ November Exam

Interacción con GUIs

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

PIC 20A GUI with swing

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

CS 251 Intermediate Programming GUIs: Event Listeners

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

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

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

FORMAS DE IMPLEMENTAR LOS OYENTES. A).- El oyente en una clase independiente con el constructor con un argumento y usando el método getactioncommand.

(Incomplete) History of GUIs

Chapter 14. More Swing

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

CS 2113 Software Engineering

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

Unit - 2 Abstract Window Toolkit

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

Advanced Java Programming

CS11 Java. Fall Lecture 3

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

I/O. Output. Input. Input ของจาวา จะเป น stream จะอ าน stream ใช คลาส Scanner. standard input. standard output. standard err. command line file.

MIT AITI Swing Event Model Lecture 17

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

Computer Science 210: Data Structures. Intro to Java Graphics

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

Basicsof. JavaGUI and SWING

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

The Abstract Window Toolkit

PESIT Bangalore South Campus

Graphical User Interfaces 2

CSA 1019 Imperative and OO Programming

Lab 10: Structs and Enumeration

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

7. Program Frameworks

CSE 8B Intro to CS: Java

Java Programming Lecture 6

G51PRG: Introduction to Programming Second semester Applets and graphics

Handling Mouse and Keyboard Events

COMPSCI 230. Software Design and Construction. Swing

The AWT Package, An Overview

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

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

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

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

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

Transcription:

กล ม API ท ใช Programming Graphical User Interface (GUI) AWT (Abstract Windowing Toolkit) และ Swing. AWT ม ต งต งแต JDK 1.0. ส วนมากจะเล กใช และแทนท โดยr Swing components. Swing API ปร บปร งความสามารถเพ มเต มจาก AWT อย ในร ป ของJava Foundation Classes (JFC) ซ งประกอบด วย Swing, Java2D, Accessibility, Internationalization และ Pluggable Look-and- Feel Support APIs ซ งม มาต งแต จาวาร นท 1.2 Programming GUI with AWT AWT Packages java.awt package บรรจ AWT graphics classes หล ก: GUI Component classes เช น Button, TextField, and Label, GUI Container classes เช น Frame and Panel, Layout managers เช น FlowLayout, BorderLayout and GridLayout, Custom graphics classes เช น Graphics, Color and Font. java.awt.event package สน บสน นการจ ดการเหต การณ (event handling) : Event classes เช น ActionEvent, MouseEvent, KeyEvent และ WindowEvent, Event Listener Interfaces เช น ActionListener, MouseListener, KeyListener and WindowListener, Event Listener Adapter classes เช น MouseAdapter, KeyAdapter, and WindowAdapter. Containers and Components Component: เป นคอมโพเนนต พ นฐานเช น Button, Label, และ TextField. Container: เช น Frame and Panel ใช ส าหร บบรรจ คอมโพเนนต อ น ด วยเลเอาต ต าง ๆ เช น FlowLayout หร อ GridLayout. container สามารถสร างซ อนก นได Panel pnl = new Panel(); // Panel is a container Button btn = new Button("Press"); // Button is a component pnl.add(btn); // The Panel container adds a Button component Top-Level Containers: Frame, Dialog Frame AWT Container Classes import java.awt.frame; // Using Frame class in package java.awt // A GUI program is written as a subclass of Frame - the top-level container // This subclass inherits all properties from Frame, e.g., title, icon, buttons, content-pane public class MyGUIProgram extends Frame { AWT Dialog เป น "pop-up window" แสดงข าวสารเพ อการต ดต อก บผ ใช สามารถก าหนดค า title-bar (containing an icon, a title and a close button) และ เน อหาท แสดง (a content display area) as illustrated // private variables // Constructor to setup the GUI components public MyGUIProgram() { // methods // Invoke the constructor (to setup the GUI) by allocating an instance new MyGUIProgram(); 1

Secondary Containers: Panel and ScrollPane บรรจ ใน top-level Panel: ใช ก บ layout เช น grid หร อ flow layout. ScrollPane: สามารถเล อนด คอมโพเนนต ท อย ข างในท งแนวด งและ แนวราบ Hierarchy of the AWT Container Classes AWT Component Classes Button, TextField, Label, Checkbox, CheckboxGroup (radio buttons), List, และ Choice Constructors java.awt.label public Label(String strlabel, int alignment); // Construct a Label with the given text String, of the text alignment public Label(String strlabel); // Construct a Label with the given text String public Label(); // Construct an initially empty Label Constants (final static fields) Public Methods public static final LEFT; // Label.LEFT public static final RIGHT; // Label.RIGHT public static final CENTER; // Label.CENTER // Examples public String gettext(); public void settext(string strlabel); public int getalignment(); public void setalignment(int alignment); 2

Example Label lblinput; // Declare an Label instance called lblinput lblinput = new Label("Enter ID"); // Construct by invoking a constructor via the new operator add(lblinput); // this.add(lblinput) - "this" is typically a subclass of Frame lblinput.settext("enter password"); // Modify the Label's text string lblinput.gettext(); // Retrieve the Label's text string An Anonymous Instance // Allocate an anonymous Label instance. // "this" container adds the instance. // You CANNOT reference an anonymous instance to carry out further operations. add(new Label("Enter Name: ", Label.RIGHT)); // Same as Label xxx = new Label("Enter Name: ", Label.RIGHT)); // xxx assigned by compiler add(xxx); java.awt.button Constructors public Button(String btnlabel); // Construct a Button with the given label public Button(); // Construct a Button with empty label Public Methods public String getlabel(); // Get the label of this Button instance public void setlabel(string btnlabel); // Set the label of this Button instance public void setenable(boolean enable); // Enable or disable this Button. Disabled Button cannot be clicked. Example Button btncolor = new Button("Red"); // Declare and allocate a Button instance called btncolor add(btncolor); // "this" Container adds the Button... btncolor.setlabel("green"); // Change the button's label btncolor.getlabel(); // Read the button's label... add(button("blue")); Constructors java.awt.textfield public TextField(String initialtext, int columns); // Construct a TextField instance with the given initial text string with the number of columns. public TextField(String initialtext); // Construct a TextField instance with the given initial text string. public TextField(int columns); // Construct a TextField instance with the number of columns. Public Methods public String gettext(); // Get the current text on this TextField instance public void settext(string strtext); // Set the display text on this TextField instance public void seteditable(boolean editable); // Set this TextField to editable (read/write) or non-editable (read-only) Example TextField tfinput = new TextField(30); // Declare and allocate an TextField instance called tfinput add(tfinput); // "this" Container adds the TextField TextField tfresult = new TextField(); // Declare and allocate an TextField instance called tfresult tfresult.seteditable(false) ; // Set to read-only add(tfresult); // "this" Container adds the TextField // Read an int from TextField "tfinput", square it, and display on "tfresult". // gettext() returns a String, need to convert to int int number = Integer.parseInt(tfInput.getText()); number *= number; // settext() requires a String, need to convert the int number to String. tfresult.settext(number + ""); 3

Example 1: AWTCounter import java.awt.*; // Using AWT container and component classes import java.awt.event.*; // Using AWT event classes and listener interfaces // An AWT program inherits from the top-level container java.awt.frame public class AWTCounter extends Frame implements ActionListener { private Label lblcount; // Declare a Label component private TextField tfcount; // Declare a TextField component private Button btncount; // Declare a Button component private int count = 0; // Counter's value // Constructor to setup GUI components and event handlers public AWTCounter () { setlayout(new FlowLayout()); // "super" Frame, which is a Container, sets its layout to FlowLayout to arrange // the components from left-to-right, and flow to next row from top-to-bottom. lblcount = new Label("Counter"); // construct the Label component add(lblcount); // "super" Frame container adds Label component tfcount = new TextField("0", 10); // construct the TextField component tfcount.seteditable(false); // set to read-only add(tfcount); // "super" Frame container adds TextField component btncount = new Button("Count"); // construct the Button component add(btncount); // "super" Frame container adds Button component btncount.addactionlistener(this); // "btncount" is the source object that fires an ActionEvent when clicked. // The source add "this" instance as an ActionEvent listener, which provides // an ActionEvent handler called actionperformed(). // Clicking "btncount" invokes actionperformed(). settitle("awt Counter"); // "super" Frame sets its title setsize(250, 100); // "super" Frame sets its initial window size // For inspecting the Container/Components objects // System.out.println(this); // System.out.println(lblCount); // System.out.println(tfCount); // System.out.println(btnCount); setvisible(true); // "super" Frame shows // System.out.println(this); // System.out.println(lblCount); // System.out.println(tfCount); // System.out.println(btnCount); // Invoke the constructor to setup the GUI, by allocating an instance AWTCounter app = new AWTCounter(); // or simply "new AWTCounter();" for an anonymous instance // ActionEvent handler - Called back upon button-click. ++count; // Increase the counter value // Display the counter value on the TextField tfcount tfcount.settext(count + ""); // Convert int to String Example 2: AWTAccumulator // An AWT GUI program inherits from the top-level container java.awt.frame public class AWTAccumulator extends Frame implements ActionListener { private Label lblinput; // Declare input Label private Label lbloutput; // Declare output Label private TextField tfinput; // Declare input TextField private TextField tfoutput; // Declare output TextField private int sum = 0; // Accumulated sum, init to 0 // Constructor to setup the GUI components and event handlers public AWTAccumulator() { setlayout(new FlowLayout()); // "super" Frame (container) sets layout to FlowLayout, which arranges // the components from left-to-right, and flow to next row from top-to-bottom. lblinput = new Label("Enter an Integer: "); // Construct Label add(lblinput); // "super" Frame container adds Label component tfinput = new TextField(10); // Construct TextField add(tfinput); // "super" Frame adds TextField tfinput.addactionlistener(this); // "tfinput" is the source object that fires an ActionEvent upon entered. // The source add "this" instance as an ActionEvent listener, which provides // an ActionEvent handler called actionperformed(). // Hitting "enter" on tfinput invokes actionperformed(). lbloutput = new Label("The Accumulated Sum is: "); // allocate Label add(lbloutput); // "super" Frame adds Label tfoutput = new TextField(10); // allocate TextField tfoutput.seteditable(false); // read-only add(tfoutput); // "super" Frame adds TextField settitle("awt Accumulator"); // "super" Frame sets title setsize(350, 120); // "super" Frame sets initial window size setvisible(true); // "super" Frame shows AWT Event-Handling // Invoke the constructor to setup the GUI, by allocating an anonymous instance new AWTAccumulator(); // ActionEvent handler - Called back upon hitting "enter" key on TextField // Get the String entered into the TextField tfinput, convert to int int numberin = Integer.parseInt(tfInput.getText()); sum += numberin; // Accumulate numbers entered into sum tfinput.settext(""); // Clear input TextField tfoutput.settext(sum + ""); // Display sum on the output TextField // convert int to String 4

// A MouseListener interface, which declares the signature of the handlers // for the various operational modes. public interface MouseListener { public void mousepressed(mouseevent evt); // Called back upon mouse-button pressed public void mousereleased(mouseevent evt); // Called back upon mouse-button released public void mouseclicked(mouseevent evt); // Called back upon mouse-button clicked (pressed and released) public void mouseentered(mouseevent evt); // Called back when mouse pointer entered the component public void mouseexited(mouseevent evt); // Called back when mouse pointer exited the component // An example of MouseListener, which provides implementation to the handler methods class MyMouseListener implement MouseListener { public void mousepressed(mouseevent e) { System.out.println("Mouse-button pressed!"); public void mousereleased(mouseevent e) { System.out.println("Mouse-button released!"); public void mouseclicked(mouseevent e) { System.out.println("Mouse-button clicked (pressed and released)!"); public void mouseentered(mouseevent e) { System.out.println("Mouse-pointer entered the source component!"); public void mouseexited(mouseevent e) { System.out.println("Mouse exited-pointer the source component!"); AWTCounter: ActionEvent and ActionListener Interface public interface ActionListener { public void actionperformed(actionevent evt); // Called back upon button-click (on Button), enter-key pressed (on TextField) public class AWTCounter extends Frame implements ActionListener { // "this" is chosen as the ActionEvent listener, hence, it is required // to implement ActionListenerinterface // Implementing ActionListener interface requires this class to provide implementation // to the abstract method actionperformed() declared in the interface. // Programmed response upon activation // Increment the count value and display on the TextField ++count; tfcount.settext(count + ""); btncount.addactionlistener(this); ActionEvent evt = new ActionEvent( ); listener.actionperformed(evt); // for all its listener(s) Revisit Example 2 AWTAccumulator: ActionEvent and ActionListener Interface We identify the tfinput (TextField) as the source object. Hitting the "Enter" key on a TextField fires an ActionEvent to all its ActionEvent listener(s). We choose this object as the ActionEvent listener (for simplicity). The source object tfinput (TextField) registers the listener (this object) via the tfinput.addactionlistener(this). The ActionEvent listener (this class) is required to implement the ActionListener interface, and override the actionperformed() method to provide the programmed response upon activation. 5

Example 3: WindowEvent and WindowListener Interface public void windowclosing(windowevent evt) // Called-back when the user attempts to close the window by clicking the window close button. // This is the most-frequently used handler. public void windowopened(windowevent evt) // Called-back the first time a window is made visible. public void windowclosed(windowevent evt) // Called-back when a window has been closed as the result of calling dispose on the window. public void windowactivated(windowevent evt) // Called-back when the Window is set to be the active Window. public void windowdeactivated(windowevent evt) // Called-back when a Window is no longer the active Window. public void windowiconified(windowevent evt) // Called-back when a window is changed from a normal to a minimized state. public void windowdeiconified(windowevent evt) // Called-back when a window is changed from a minimized to a normal state. import java.awt.*; // Using AWT containers and components import java.awt.event.*; // Using AWT events classes and listener interfaces // An AWT GUI program inherits the top-level container java.awt.frame public class WindowEventDemo extends Frame implements ActionListener, WindowListener { // This class acts as listener for ActionEvent and WindowEvent // A Java class can extend only one superclass, but it can implement multiple interfaces. private TextField tfcount; // Declare a TextField component private Button btncount; // Declare a Button component private int count = 0; // Counter's value // Constructor to setup the GUI components and event handlers public WindowEventDemo() { setlayout(new FlowLayout()); // "super" Frame sets to FlowLayout add(new Label("Counter")); // "super" Frame adds an anonymous Label tfcount = new TextField("0", 10); // Construct the TextField tfcount.seteditable(false); // read-only add(tfcount); // "super" Frame adds TextField btncount = new Button("Count"); // Construct the Button add(btncount); // "super" Frame adds Button btncount.addactionlistener(this); // btncount (source object) fires ActionEventupon clicking // btncount adds "this" object as an ActionEvent listener addwindowlistener(this); // "super" Frame (source object) fires WindowEvent. // "super" Frame adds "this" object as a WindowEvent listener. settitle("windowevent Demo"); // "super" Frame sets title setsize(250, 100); // "super" Frame sets initial size setvisible(true); // "super" Frame shows new WindowEventDemo(); // Let the construct do the job /* ActionEvent handler */ ++count; tfcount.settext(count + ""); /* WindowEvent handlers */ // Called back upon clicking close-window button public void windowclosing(windowevent evt) { System.exit(0); // Terminate the program // Not Used, but need to provide an empty body to compile. public void windowopened(windowevent evt) { public void windowclosed(windowevent evt) { public void windowiconified(windowevent evt) { public void windowdeiconified(windowevent evt) { public void windowactivated(windowevent evt) { public void windowdeactivated(windowevent evt) { 6. Layout Managers and Panel 6