Chapter 1 GUI Applications

Similar documents
CSE 8B Intro to CS: Java

Graphical Interfaces

BM214E Object Oriented Programming Lecture 13

Graphical Interfaces

Swing from A to Z Some Simple Components. Preface

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

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 - Applications. The following code sets up an application with a drop down menu, as yet the menu does not do anything.

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

Advanced Java Programming (17625) Event Handling. 20 Marks

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

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

User interfaces and Swing

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

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

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

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

GUI in Java TalentHome Solutions

CSIS 10A Practice Final Exam Solutions

Handling Mouse and Keyboard Events

More Swing. CS180 Recitation 12/(04,05)/08

G51PRG: Introduction to Programming Second semester Applets and graphics

Computer Science 210: Data Structures. Intro to Java Graphics

Programming Mobile Devices J2SE GUI

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

Systems Programming Graphical User Interfaces

Programming Languages and Techniques (CIS120e)

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

Unit 7: Event driven programming

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

CSSE 220. Event Based Programming. Check out EventBasedProgramming from SVN

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

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

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

Graphical User Interfaces 2

Java Programming Unit 6. Inner Classes. Intro to Apples. Installing Apache Tomcat Server.

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

(Incomplete) History of GUIs

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

The AWT Package, Placing Components in Containers, CardLayout. Preface. Introduction

Window Interfaces Using Swing Objects

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

Lecture 5: Java Graphics

Window Interfaces Using Swing Objects

GUI Programming: Swing and Event Handling

Dr. Hikmat A. M. AbdelJaber

Advanced Java Programming

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

The AWT Package, Graphics- Introduction to Images

PESIT Bangalore South Campus

GUI Forms and Events, Part II

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

Chapter 14. More Swing

H212 Introduction to Software Systems Honors

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Graphical User Interfaces 2

7. Program Frameworks

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,

Java. GUI building with the AWT

GUI 4.1 GUI GUI MouseTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; /* 1 */

Java - Applets. public class Buttons extends Applet implements ActionListener

Programmierpraktikum

CHAPTER 2. Java Overview

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

Graphical User Interfaces 2

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

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

HW#1: Pencil Me In Status!? How was Homework #1? Reminder: Handouts. Homework #2: Java Draw Demo. 3 Handout for today! Lecture-Homework mapping.

Programming Language Concepts: Lecture 8

Interacción con GUIs

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

SD Module-1 Advanced JAVA

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

Lecture 3: Java Graphics & Events

SD Module-1 Advanced JAVA. Assignment No. 4

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

Windows and Events. created originally by Brian Bailey

UCLA PIC 20A Java Programming

CompSci 230 Software Construction

CS 120 Fall 2008 Practice Final Exam v1.0m. Name: Model Solution. True/False Section, 20 points: 10 true/false, 2 points each

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!

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1

Week 9. Abstract Classes

Lecture 19 GUI Events

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a

CSA 1019 Imperative and OO Programming

CSIS 10A PRACTICE FINAL EXAM Name Closed Book Closed Computer 3 Sheets of Notes Allowed

CSE 331 Software Design & Implementation

1 of :32:42

Using the API: Introductory Graphics Java Programming 1 Lesson 8

Building Graphical User Interfaces with the MVC Pattern

Programming: You will have 6 files all need to be located in the dir. named PA4:

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.

CSCI 053. Week 5 Java is like Alice not based on Joel Adams you may want to take notes. Rhys Price Jones. Introduction to Software Development

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

Chapter 11 Handling Exceptions and Events. Chapter Objectives

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Transcription:

Chapter 1 GUI Applications 1. GUI Applications So far we've seen GUI programs only in the context of Applets. But we can have GUI applications too. A GUI application will not have any of the security limitations of an applet. It does not run in a "sandbox" and can access your PC's file system just like standard Java applications. The good news is that all of the GUI concepts we learned for applets apply to applications. There is only one issue we have to deal with - and that's the creation and management of the top-level application window. Applets automatically took care of this for us. When we extended the Applet class we automatically got access to a window or a container. Its size was determined by the "height" and "width" parameters of the APPLET tag in our HTML file. However when we write Java GUI applications - we need to create that initial application window ourselves. We do this by having our program extend Frame (a top-level window container), instead of Applet and using the constructor in place of init(). Let's see this in code. 01 import java.awt.*; 02 import java.awt.event.*; 03 04 class GUIApplication extends Frame implements ActionListener { 05 06 TextField input; 07 TextField output; 08 Button copy; 09 10 public GUIApplication() { 11 super("my GUI Application"); 12 13 input = new TextField(15); 14 output = new TextField(15); 15 output.seteditable(false); 16 copy = new Button("Copy ->"); 17 copy.addactionlistener(this); 18 19 setlayout(new FlowLayout()); 20 add(input); 21 add(copy); 22 add(output); 23 24 this.addwindowlistener 25 (new WindowListener() { 26 public void windowclosing(windowevent e) { 27 System.exit(0); 28 } 29 public void windowclosed(windowevent e) { 30 } 31 public void windowopened(windowevent e) { 32 } 1

33 public void windowiconified(windowevent e) { 34 } 35 public void windowdeiconified(windowevent e) { 36 } 37 public void windowactivated(windowevent e) { 38 } 39 public void windowdeactivated(windowevent e) { 40 } 41 } 42 ); 43 44 setsize(400,200); 45 } 46 47 public void actionperformed(actionevent ev) { 48 String userinput = input.gettext(); 49 output.settext(userinput); 50 } 51 52 public static void main(string args[]) { 53 54 GUIApplication app = new GUIApplication(); 55 app.setvisible(true); 56 57 } 58 } Here's we have a class namd: GUIApplication (line 4). It extends Frame - instead of Applet - to provide itself with a GUI window. Just like an applet it implements ActionListner. Of course we can also use inner classes to handle events. The constructor for our class is where we instantiate and initialize the GUI components (lines: 10-45). This is equivalent to our applet's init() method. Here we instantiate a couple of text boxes and a button (lines 13,14,16). As we did with applets - we put the references outside of our methods (lines 6-8). In that way they can be accessed by all methods within our class. We register ourselves as a listener for "copy" button (line 17). We set the layout next (line 19). Now we can add our components (lines: 20-22). Let's not forget our actionperformed() method (lines 47-50). There are still a few more extra steps to perform. First: remember our rule about constructors in an extended class? If we are extending a class we should always call our superclass' constructor as the first statement in our constructor. If we don't, Java will automatically add a no parameter constructor which may not be the constructor we want. We didn't worry about this when we were writing Applets because we never wrote constructors. We used init() instead. Since we're extending Frame we need to call its constructor. Frame has a few constructors, one lets us add a title to our frame. That's the one we'll use (line 11). We also need to add a call to setsize() to explicitly set the size of the frame to a particular width and height in pixels (line 44). Remember in Applets, the "height" and "width" 2

parameters in the HTML's APPLET tag determined the size of our window. In a GUI application, the method setsize() does this work. Finally, we need to take care of the situation where the user clicks on the window's exit button. The default behavior hides our window but does not exit our application. The correct way is to implement a Window Listener against our frame so we can catch all the Window Events: windowclosing windowclosed windowopened windowiconified windowdeiconified windowactivated windowdeactivated To do this you simply call an addwindowlistener() on our Frame. We want to add the listener to our current frame - and not to a particular component. We can use the "this" keyword to make this less ambiguous (line 24). We also use an anonymous class to make things simple (lines 25-42). WindowClosing is the event we want (lines 26-28). We just exit the application whenever the close window icon is clicked (line 27). We're done with our GUI class but we still have to instantiate and run it. So we create a main() method to instantiate and run this class (lines 52-57). We instantiate an instance of our Frame class. In effect starting our application. We then make it visible by calling setvisible:true. Our window will not be visible until this call. We could have put the SetVisible statement inside our constructor - after setsize(). In that case our Frame would have made itself visible after all the components were added. But in a real world program we may have multiple windows. For example: A Frame, a couple of Dialog boxes and some other window. We may also have to instantiate other non- GUI objects. In such a program we would instantiate all our windows in main() but keep them hidden. When all the instantiations are completed we would make our main window visible and let our users work with our program. However our current GUI application is very simple. It only has a single Frame. This Frame class not only represents our main GUI window but also our entire application's business logic. Since this is an application, we have no need for an HTML page We just compile and run. C> javac GUIApplication.java C> java GUIApplication 3

When writing GUI applications, it may be necessary to insert debugging statements at critical points in your programs. You can use the console I/O's "print" statement for this purpose. The outputs from these statements appear on the console. 2. Graphics Applications Java Applications can also be used for drawing images. This is quiet similar to the way applets work. Let's write a Java application that paints a dot every time the user clicks on the application window. 01 import java.awt.*; 02 import java.awt.event.*; 03 04 class GraphicsApplication extends Frame implements MouseListener { 05 06 int xpos = 100; 07 int ypos = 50; 08 09 public GraphicsApplication() { 10 11 super("my Graphics Application"); 12 13 setbackground(color.yellow); 14 addmouselistener(this); 15 16 addwindowlistener 17 (new WindowAdapter() { 18 public void windowclosing(windowevent e) { 19 System.exit(0); 20 } 21 } 22 ); 23 24 setsize(300,200); 25 } 26 27 public static void main(string args[]) { 28 29 GraphicsApplication app = new GraphicsApplication(); 30 app.setvisible(true); 31 } 32 4

33 public void paint(graphics g) { 34 g.setcolor(color.red); 35 g.filloval(xpos, ypos, 5, 5); 36 } 37 38 public void mouseclicked(mouseevent e) { } 39 40 public void mousepressed(mouseevent e) { 41 xpos = e.getx(); 42 ypos = e.gety(); 43 repaint(); 44 } 45 46 public void mousereleased(mouseevent e) { } 47 48 public void mouseentered(mouseevent e) { } 49 50 public void mouseexited(mouseevent e) { } 51 52 } Here's our application code. Our application extends "Frame" and implements a MouseListener (line 4). We create a main() method which instantiates an instance of the application and then makes it visible (line 27-31). In the constructor we first call our superclass constructor to give window a title (line 11). We then add the background and add the MouseListener (lines 13-14). To exit properly, we add our anonymous inner class that handles the WindowEvent (lines 16-22). Notice that we are using a WindowAdapter instead of a WindowListener. WindowAdapter is a shortcut that let us define only the methods we need. This is a lot better than having a bunch of empty methods. Finally we set the size of our frame (line 24). To draw graphics in our application we make use of the trusty paint() method (lines 33-36). Just as in Applets, all the drawing in an application needs to take place here. We draw a dot every time the user clicks in the application window (line 35). We add the listener methods next (line 38-50). On Mouse Pressed we get the x, y position and call repaint (line 40-44). Yes, there is also a MouseAdapter that we could have used in order to get rid of all these empty methods. 3. MVC Programming In a simple GUI application most of your application's logic is intermixed with your GUI code. However when you start writing large applications this type of programming could lead to a very messy code. Professional programmers always try to separate the application logic from its GUI. Objectoriented languages - like Java - make this quiet easy. In fact object oriented programming has 5

a term for this type of design. this is known as Model-View-Controller or MVC programming. In this type of programming the "model", is the code that encapsulates your application's logic. The "view" is the code that encapsulates the GUI portions, and the "controller" is the code that connects the two together. The idea behind MVC programming is to create applications that are easy to understand and maintain. Let's assume we need to write a program that can convert temperatures between Fahrenheit and Celsius. The formula is quiet easy. To go to Celsius you first subtract 32, then multiply by 5 and finally divided by 9. To go to Fahrenheit you multiply by 9, divide by 5 and then add 32. This logic can of course be encapsulated in a class. 01 class CF { 02 03 public double tofahrenheit(double c) { 04 05 return ( c * (9.0/5.0) + 32); 06 } 07 08 public double tocelsius(double f) { 09 10 return ( (f - 32) * (5.0/9.0)); 11 } 12 13 } Here's our class. It provides 2 methods. One to convert to Celsius (lines 8-11) and another to convert to Fahrenheit (3-6). This class represents our application's logic or model. It contains no User interface code. Of course in a real world program, your application's logic may be made up of many classes. Let's write our view. 01 import java.awt.*; 02 import java.awt.event.*; 03 04 class FahrenheitToCelsius extends Frame implements ActionListener { 05 06 TextField input; 07 TextField output; 08 Button toc; 09 CF cf; 10 11 public FahrenheitToCelsius() { 12 super("fahrenheit to Celsius"); 13 14 input = new TextField(15); 15 output = new TextField(15); 16 output.seteditable(false); 17 toc = new Button("To Celsius"); 18 toc.addactionlistener(this); 19 20 cf = new CF(); 6

21 22 setlayout(new FlowLayout()); 23 add(input); 24 add(toc); 25 add(output); 26 27 this.addwindowlistener 28 (new WindowAdapter() { 29 public void windowclosing(windowevent e) { 30 System.exit(0); 31 } 32 } 33 ); 34 35 setsize(400,200); 36 } 37 38 public void actionperformed(actionevent ev) { 39 String txt = input.gettext(); 40 double d = Double.parseDouble(txt); 41 double cel = cf.tocelsius(d); 42 String s = Double.toString(cel); 43 output.settext(s); 44 } 45 46 public static void main(string args[]) { 47 48 FahrenheitToCelsius app = new FahrenheitToCelsius(); 49 app.setvisible(true); 50 51 } 52 } Here's a basic GUI application class. It has a main() method (lines 46-51), and a constructor (lines 11-36). We add a text box for our input, and Another for our output (lines 14-15). There's also a button to trigger a conversion from Fahrenheit to Celsius (line 17). We could just as easily add another button for a conversion of Celsius to Fahrenheit but we want to keep our program simple. We add an event handler to our button at line 18. Our application (or view) contains no business logic. To add the required logic, we need to instantiate an object of type CF. The best place is in the constructor (line 20). With the object in hand, we can now do our conversion. In our actionperformed(), we get the input, convert it to a number and call the correct method on our object (lines 39-41). We display the results at line 43. Notice we have to convert our result back to a string (line 42). Separating an application's logic from its view makes a lot of sense, especially in large programs. 7

Besides easy maintenance, an MVC program can be ported to different platforms without much effort. For example, by simply replacing the view portion of our code, we can create an applet version or of our application. 8