Computer Programming Java AWT Lab 18

Similar documents
GUI in Java TalentHome Solutions

The AWT Event Model 9

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

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

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

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

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

CHAPTER 2. Java Overview

Advanced Java Programming (17625) Event Handling. 20 Marks

Programming Mobile Devices J2SE GUI

Graphical User Interfaces 2

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

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

G51PRG: Introduction to Programming Second semester Applets and graphics

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

SD Module-1 Advanced JAVA

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

SD Module-1 Advanced JAVA. Assignment No. 4

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

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

Unit 7: Event driven programming

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

Handling Mouse and Keyboard Events

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Outline. More on the Swing API Graphics: double buffering and timers Model - View - Controller paradigm Applets

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

Graphic User Interfaces. - GUI concepts - Swing - AWT

Graphical User Interfaces 2

COMPSCI 230. Software Design and Construction. Swing

Interacción con GUIs

Graphical User Interfaces 2

BM214E Object Oriented Programming Lecture 13

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

GUI Event Handlers (Part II)

Java Applets / Flash

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!

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

Java. GUI building with the AWT

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

GUI Programming: Swing and Event Handling

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

CSC207H: Software Design Lecture 11

Mobile MOUSe JAVA2 FOR PROGRAMMERS ONLINE COURSE OUTLINE

IPM 12/13 P4 Handling Events in AWT

User interfaces and Swing

Java Coordinate System

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

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

Basicsof. JavaGUI and SWING

Introduction to the JAVA UI classes Advanced HCI IAT351

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

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

GUI Event Handlers (Part I)

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

Sri Vidya College of Engineering & Technology

Advanced Java Programming

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

encompass a group of features for building Graphical User Interfaces (GUI).

Graphical Interfaces

Java Event Handling -- 1

Packages: Putting Classes Together

Computer Science 210: Data Structures. Intro to Java Graphics

Essential Series. Springer-Verlag London Ltd.

Java Applet Basics. Life cycle of an applet:

Java AWT Windows, Text, & Graphics

Programming graphics

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1,

cs Java: lecture #5

Chapter 14: Applets and More

Chapter 12 Advanced GUIs and Graphics

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

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

CS11 Java. Fall Lecture 4

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

Chapter 14: Applets and More

Here is a list of a few of the components located in the AWT and Swing packages:

8/23/2014. Chapter Topics. Introduction to Applets. Introduction to Applets. Introduction to Applets. Applet Limitations. Chapter 14: Applets and More

Chapter 1 GUI Applications

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

CS 2113 Software Engineering

The AWT Component Library 10

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

CS 315 Software Design Homework 1 First Sip of Java Due: Sept. 10, 11:30 PM

Graphical Interfaces

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

Java - Applets. public class Buttons extends Applet implements ActionListener

10/16/2008. CSG 170 Round 5. Prof. Timothy Bickmore. User Analysis Task Analysis (6) Problem Scenarios (3)

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

Graphical User Interfaces in Java - SWING

CS11 Java. Fall Lecture 3

Dr. Hikmat A. M. AbdelJaber

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Graphical User Interface (GUI)

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

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

Systems Programming Graphical User Interfaces

Lecture 3: Java Graphics & Events

2010 가을학기부산대학교정보컴퓨터공학부 OVERVIEW OF GUI PROGRAMMING

Transcription:

Computer Programming Java AWT Lab 18 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University Copyrights 2015 DCSLab. All Rights Reserved

Overview AWT Basic Use AWT AWT Event Specific things

What is the AWT? Classes which have a collection of common graphic functions supporting several GUI platforms A Classical method of windows programming Based on system executing GUI graphic heavyweight component java.awt.* Function Control and manage graphic contexts Draw shapes and text You have to import this Control and manage images So use Swing Swing is light component

Why we have to know AWT? Two kinds of user interface CUI (Character User Interface) GUI (Graphical User Interface) Many programs are based on GUI Windows, Media Player, Editplus, games etc. In java, you can programming GUI using AWT and Swing

AWT Components

How to use Components 1. Generate a component Button mybutton= new Button( my button"); 2. Add component on Container add(mybutton); 3. Connect event listenner and evert control rutine MyActionListener mal= new MyActionListener(); mybutton.addactionlistener(mal);

Overview AWT Basic Use AWT AWT Event Specific things

Event Event Response about user s behavior about UI components Programming based on event Using busy waiting, watch user s behavior and response about that.

Event Handling java.awt.event Provide interfaces and class for handle several events from AWT component xxxlistener, xxxevent, xxxadapter Interface Class Delegated event handling model Register object(event listener) at Component(event source) for event handling

Kinds of event Low-Level event and Semantic event Low-Level event System level events resulted from User s input or component s function Kinds of Low-Level event java.awt.event.componentevent java.awt.event.focusevent java.awt.event.keyevent java.awt.event.mouseevent java.awt.event.windowevent Semantic event Using Low-Level event, make a second event (e.g) mouse click-> pressed, released 2kinds of Low-Level event occur => Handled by ActionEvent Kinds of Semantic event java.awt.event.actionevent java.awt.event.adjustmentevent java.awt.event.itemevent java.awt.event.textevent In practical event handling, these are not distinguished Handling Semantic event is more efficient

Step for calling event listener processevent When event occur at component, call event listener processevent processfocusevent processmouseevent FocusListener processkeyevent Commonly called Handler processcomponentevent e.g) FocusEvent processevent => processfocusevent => FocusListener, and process it based on ID

Event class and Event listener Classify kinds of event that can be occur at component Event classes have information and method about event Fixed event at each components Button event ActionEvent, ComponentEvent, FocusEvent, KeyEvent, MouseEvent Components that ActionEvent can be occur Button, List, MenuItem, TextField Etc. referencing API

Hierarchy of event classes

Event class and Event listener Listener is interface handling events xxxevent class maps onto xxxlistener xxxlistener have method handling low-level event E.g - KeyListener handling KeyEvent void keypressed(keyevent e) void keyreleased(keyevent e) void keytyped(keyevent e)

Event handling process Decide the event to handle E.g ActionEvent Define a class which include event listener E.g MyListener is a class Implementing ActionListenerClass MyListener implements ActionListner{ } Implement void actionperformed(actionevent e) Each listener has different implement (referencing API) Generate an object and register it as event listener this.addactionlistener(new MyListener());

Event adapter Easy to handling low-level event Listener interface which has event handling methods over 2(xxxListener)and Adapter class which implement those things. Each event handling method is empty block If there is adapter, define inherited class instead of implementing listener Overriding

ActionEvent and ActionListener Major methods of ActionListener void actionperformed(actionevent ev) Example of event occurrence Click a button Click a menu Press enter key at TextField Double click a element of list Major methods of ActionEvent String getactioncommand() Return a command name Object getsource() Inherited method at EventObject

WindowEvent and WindowListener Major methods of WindowListener Case changing the state of windows void windowactivated(windowevent ev) void windowclosed(windowevent ev) Major methods of WindowEvent int getnewstate() 0 is common state int getoldstate() Window getwindow()

ItemEvent and ItemListener Major methods of ItemListener void itemstatechanged(itemevent ev) Select Item or release item at Checkbox, CheckboxMenuItem, Choice, List Major methods of ItemEvent Object getitem() int getstatechange() String paramstring()

AdjustmentEvent and AdjustmentListener Major methods of AdjustmentListenervoid adjustmentvaluechanged(adjustmentevent ev) Case changing the state of scroll bar Major methods of AdjustmentEvent int getvalue() int getadjustmenttype() UNIT_INCREMENT, UNIT_DECREMENT, BLOCK_INCREMENT,BLOCK_DECREMENT, TRACK

KeyEvent and KeyListener When event related with Keystrock occurs, KeyEvent occurs Major methods of KeyListener keypressed(keyevent ev) keyreleased(keyevent ev) keytyped(keyevent ev) Major methods of KeyEvent char getkeychar() int getkeycode() int getkeylocation() static String getkeytext(int keycode) static String getkeymodifierstext(int)

MouseEvent and listener When event related with a mouse occurs, MouseEvent occurs Major methods of MouseListener mouseclicked(mouseevent ev) mousepressed(mouseevent ev) mousereleased(mouseevent ev) Major methods of MouseMotionListener mousedragged(mouseevent ev) mousemoved(mouseevent ev) Major methods of MouseEvent int getbutton() Point getpoint()

TextEvent and FocusEvent Major methods of TextListenertextValueChanged(TextEvent ev) When texts are changed at TextArea and TextFiled, event occurs and listener executes Major methods of FocusListener When component gets or misses input focus, event occurs and listener executes focusgained(focusevent ev) focuslost(focusevent ev)

Overview AWT Basic Use AWT AWT Event Specific things

Graphic Context Environments for Graphic tasks EX) coordinates, background color, foreground color, font Major characteristic managed by graphic context Object to be drawn : target object that graphic object will draw Coordinate system : coordinate information for drawing base Current clipping area : clipping information Clipping area save information of area to be redrawn Current color and font : information of color and font for drawing

Coordinate System General coordinate system in computer graphic Left top is (0, 0) X-axis increases to right side Y-axis increases to down side (0, 0) Component Ex) Case of Rectangle width * height (width-1, height-1)

Layout Manager Manage Position Manage component position attached to container Type of Layout BorderLayout BoxLayout CardLayout FlowLayout GridBagLayout GridLayout SprintLayout

Role of Layout Manager Without Layout Manager With Layout Manager

Hot to Set Layout 1. Create layout manager BorderLayout bm= new BorderLayout(); 2. Set layout manager of component setlayout(bm); 3. Add component add(mybutton); Arguments varies with layout manager See layout class in API for more information

BorderLayout Organize layout like the picture on the left Site image on the specific position with argument adding component public LayoutFrame(){ setlayout(new BorderLayout()); add(new Button("North"), BorderLayout.NORTH); add(new Button("South"), BorderLayout.SOUTH); add(new Button("East"), BorderLayout.EAST); add(new Button("West"), BorderLayout.WEST); add(new Button("Center"), BorderLayout.CENTER); }

Color and Font Color Use for setting graphic object color. R, G, B and Alpha Major constructor Font Color(float r, float g, float b, float a) Color(int r, int g, int b, int a) Font type and size used for printing text on the screen BOLD, ITALIC, PLAIN Major method getfont(), setfont(font font) See API for more information

Draw Shape Fill in Shape : start with fill. Ex) fillarc, fillrect Draw shape outline : start with draw. Ex) drawarc, drawrect Type of Shape Line : straight line Rect : rectangle 3Drect : 3-dimensional rectangle RoundRect : rounded rectangle Oval : ellipse Arc : an arc of circle, part of circle Polygon : polygon. Make with joining start point and endpoint

Draw Line Draw Line drawline(int x1, int y1, int x2, int y2) Draw rectangle drawrect(int x, int y, int width, int height) draw3drect(), drawroundrect(), fillrect() Draw ellipse and elliptical arc Designate rectangle that ellipse will be(inscribed ellipse) Elliptical arc is based on 3 o clock and angle goes counter clockwise direction

Draw String Draw string using method such as drawstring() Provide font character with FontMetrics Font have variable width, so letter has difference width

Toolkit Class Parent class of AWT GUI toolkit object Create various component of AWT Connect to native component of system Abstract Class Get object with Toolkit.getDefaultToolkit or gettoolkit method of Component getimage() return image object right after call Do not consider whether data is completely ready java.awt.toolkit major method Dimension getscreensize() Get total screen size int getscreenresolution() Get screen resolution (DPI: dots per inch) Image getimage(string filename) Get image according to filename Image getimage(url url) Get image according to url

Toolkit Example Toolkit example to get a lot of information public void test() { Toolkit toolkit = gettoolkit(); Dimension dim = toolkit.getscreensize(); toolkit.setdynamiclayout(true); add(new Label(" 운영체제 : "+System.getProperty("os.name"))); add(new Label(" 화면크기 : "+dim.getwidth()+" * "+dim.getheight())); add(new Label(" 화면해상도 : "+oolkit.getscreenresolution()+"dpi")); add(new Label(" 가로최대화 : "+toolkit.isframestatesupported(frame.maximized_horiz))); add(new Label(" 세로최대화 : "+toolkit.isframestatesupported(frame.maximized_vert))); add(new Label("Dynamic Layout : "+toolkit.isdynamiclayoutactive())); }

Draw Image drawimage(image img, int x, int y, Color bgcolor, ImageObserver obs) Fill area to be drawn with bgcolor, and draw image at (x, y) position ImageObserver ImageObserver object call imageupdate() method to draw image after all image date is loaded because size of image resources is big Image extension/contraction Image extension and contraction is easy with using argument of drawimage() method

Manage Image Resources All Platforms except Java Other tasks are paused until image is loaded Load all data once when creating image object Java Platform (asynchronous processing) Method call for image object create return immediately while background thread load image Ex) Print process with incomplete image data Excepting Java, Wait for loading all data complete Print process with current image data at java platform

Print Image on the Screen 1. Get name and url of image file 2. Get Toolkit object 3. Load image 4. Prepare image(trace) 5. Print image Context of constructor How to use URL url = getclass().getresource(file_name); Toolkit toolkit = Toolkit.getDefaultToolkit(); Image img = toolkit.getimage(url); URL url = new URL("http://java.sun.com/docs/books/tutorial/images/wood8.GIF"); imgexample = gettoolkit().getimage(url); Paint method public void paint(graphics g){ if ( gettoolkit().prepareimage(imgexample, -1, -1, this) == false ) { g.drawstring("wait for Loading", 100, 100); } else { g.drawimage(imgexample, 10, 10, this); } }

Create Image Button Make button more visual by Inserting image ImageButton.java public void paint(graphics g){ if (ximage == null) super.paint(g); else { /* draw image at the center of button. */ g.drawimage( ximage, (getwidth() - ximage.getwidth(this)) /2, (getheight() - ximage.getheight(this)) /2, this ); }

Organization of Menu

How to Make Menu 1. Create menu bar to attaching menu MenuBar mymenubar= new MenuBar(); 2. Create menu Menu mymenu= new Menu(" 내메뉴 "); 3. Create menu item and add in menu MenuItem mymenuitem= new MenuItem(" 내아이템 "); mymenu.add(mymenuitem); 4. Add menu in menu bar mymenubar.add(mymenu); 5. Set menu bar at frame Frame myframe= new Frame(); myframe.setmenubar(mymenubar);

Checkbox menu... Menu mymenu= new Menu(" 내메뉴 "); CheckboxMenuItem mycheckboxmenuitem= new CheckboxMenuItem(" 내체크박스메뉴 "); mymenu.add(mycheckboxmenuitem);... Use CheckboxMenuItem instead of MenuItem

Sub menu... Menu mymenu= new Menu(" 내메뉴 "); Menu mysubmenu= new Menu(" 내서브메뉴 "); MenuItem mysubmenuitem= new MenuItem(" 내서브메뉴아이템 "); mysubmenu.add(mysubmenuitem); mymenu.add(mysubmenu);... Use Menu instead of MenuItem

Exercise Download a WeeklyCalender.jar file and import it. Just fill the blank about layout. buttons, events. file i/o and string processing will be next time saveweekplan(), loadweekplan()