GUI Forms and Events, Part II

Similar documents
Graphics User Defined Forms, Part I

GUI, Events and Applets from Applications, Part III

Repetitive Program Execution

Repetition Using the End of File Condition

Arrays & Classes. Problem Statement and Specifications

SINGLE EVENT HANDLING

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

Sequential Program Execution

Editing, Compiling, Executing and Submitting Programs

DEMYSTIFYING PROGRAMMING: CHAPTER FOUR

MIT AITI Swing Event Model Lecture 17

AP CS Unit 11: Graphics and Events

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

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

Window Interfaces Using Swing Objects

Object-Oriented Programming: Revision. Revision / Graphics / Subversion. Ewan Klein. Inf1 :: 2008/09

CS Exam 1 Review Suggestions

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

Swing from A to Z Some Simple Components. Preface

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

Class 16: The Swing Event Model

Window Interfaces Using Swing Objects

To gain experience using GUI components and listeners.

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

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

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

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

Agenda. Container and Component

Introduction. Introduction

CSIS 10A Assignment 7 SOLUTIONS

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

RAIK 183H Examination 2 Solution. November 11, 2013

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

Introduction to Programming Using Java (98-388)

CS108, Stanford Handout #22. Thread 3 GUI

CMP 326 Midterm Fall 2015

CS 209 Spring, 2006 Lab 8: GUI Development Instructor: J.G. Neal

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics

RAIK 183H Examination 2 Solution. November 10, 2014

Systems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid

University of Cape Town Department of Computer Science Computer Science CSC1017F

Chapter 1 GUI Applications

Programming Language Concepts: Lecture 8

Graphical User Interface (Part-1) Supplementary Material for CPSC 233

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!

H212 Introduction to Software Systems Honors

CSC207 Week 4. Larry Zhang

Critical Thinking Assignment #6: Java Program #6 of 6 (70 Points)

CS 251 Intermediate Programming GUIs: Event Listeners

Window Interfaces Using Swing. Chapter 12

PART1: Choose the correct answer and write it on the answer sheet:

Chapter 13 Lab Advanced GUI Applications Lab Objectives. Introduction. Task #1 Creating a Menu with Submenus

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

Here are the steps to get the files for this project after logging in on acad/bill.

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

CS 251 Intermediate Programming GUIs: Components and Layout

Midterm assessment - MAKEUP Fall 2010

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

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

Java Help Files. by Peter Lavin. May 22, 2004

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

CS Fall Homework 5 p. 1. CS Homework 5

Original GUIs. IntroGUI 1

Implementing Graphical User Interfaces

CS180 Recitation. More about Objects and Methods

Java Just in Time: Collected concepts after chapter 18

CS 180 Fall 2006 Exam II

Java Programming Lecture 6

CSCI 136 Written Exam #2 Fundamentals of Computer Science II Spring 2012

Name: Checked: Learn about listeners, events, and simple animation for interactive graphical user interfaces.

An array is a type of variable that is able to hold more than one piece of information under a single variable name.

1005ICT Object Oriented Programming Lecture Notes

Lecture 5: Java Graphics

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

SampleApp.java. Page 1

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

Project 1. LibraryTest.java. Yuji Shimojo CMSC 335

University of Cape Town Department of Computer Science. Computer Science CSC117F Solutions

Queens College, CUNY Department of Computer Science. CS 212 Object-Oriented Programming in Java Practice Exam 2. CS 212 Exam 2 Study Guide

Packages: Putting Classes Together

Chapter 13 Lab Advanced GUI Applications

Introduction. Overview of the Course on Java. Overview of Part 1 of the Course

Content Area: Mathematics Course: Computer Programming Grade Level: R14 The Seven Cs of Learning

Page 1 of 7. public class EmployeeAryAppletEx extends JApplet

Here are the steps to get the files for this project after logging in on acad/bill.

Swing I CHAPTER EVENT-DRIVEN PROGRAMMING 921 Events and Listeners 921

We are on the GUI fast track path

Class 27: Nested Classes and an Introduction to Trees

Graphical User Interface (GUI)

Getting Started with Java Development and Testing: Netbeans IDE, Ant & JUnit

More About Objects and Methods

Swing I Event-Driven Programming Buttons, Events, and Other Swing Basics Containers and Layout Managers 946

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Chapter 4: Writing Classes

Swing - JTextField. Adding a text field to the main window (with tooltips and all)

Lab 5 TOC to Me. IM Client Implementation --- Part 2

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS

Calculator Class. /** * Create a new calculator and show it. */ public Calculator() { engine = new CalcEngine(); gui = new UserInterface(engine); }

Example 3-1. Password Validation

Transcription:

GUI Forms and Events, Part II Quick Start Compile step once always mkdir labs javac PropertyTax6.java cd labs Execute step mkdir 6 java PropertyTax6 cd 6 cp../5/propertytax5.java PropertyTax6.java Submit step emacs PropertyTax6.java & submit csc156abc 6 Problem Statement and Specifications This is the second part of an exercise where we present a GUI interface to the user and then based upon mouse click events, we perform certain activities. There are many types of mouse and key centered events that our programs can respond to, but we will restrict ourselves to mouse clicks for the time being. In the previous exercise, we built the GUI design that is displayed in Figure 1. Our goal in this exercise is to implement appropriate algorithms that respond to mouse clicks and calculate various tax amounts based upon input values. Assignment 6 Statement: Write a program in a file named PropertyTax6.java that uses the form shown in Figure 1 to solicit input from a user. When the calculate JButton is clicked, use the Assessment Home Value and the two Tax Rates to calculate the School and County Taxes as well as the Total Taxes. When the exit JButton is clicked, the program should shut down. All monetary amounts should be displayed with appropriate formatting. Assignment 6 Specifications: Process sample JButtons for mouse clicks Input if the exit JButton is clicked Output close the window Input if the calculate JButton is clicked Input assessment values and tax rates Process calculate school, county and total tax values Output tax values to be displayed Object Analysis and Algorithmic Development We approached the development of this algorithm in the last exercise and will need to develop it further. To begin with, we ll ignore the use of the JLabel objects other than their ability to identify the JTextField objects 1

Figure 1: Lab 6 Display for us. Arbitrarily, we will use the top 3 JTextField areas of Figure 1 as input fields. Let s refer to these as assesstf, schoolratetf and the countyratetf. The bottom 3 JTextField areas will be used for output and let s refer to these as schooltaxtf, countytaxtf and totaltaxtf. The JTextField objects have two methods that we ll be using. We ll use gettext() for input and settext() for output. Both of these methods should be thought of as manipulating String objects, as was the case with the JOptionPane methods. So we ll need methods such as Double.parseDouble() for input and String.format() for output. As we focus on the JButton objects, we ll need to discuss events and their processing in Java. The clicking of a JButton with the mouse is an action event which sends a message to an object known as an event listener. This will cause some method of the object to execute with the event as a parameter. There are 2 JButton objects in this exercise and they ll share the same event listener object. In the class statement for this object, we ll state that it implements ActionListener. This is a class that is available by name, but is not yet implemented. Such classes in Java are referred to as interfaces. The realization of the class method known as actionperformed() represents the code that will be executed when the JButton is clicked. With each JButton relying upon an action listener class to execute different lines of code, it is necessary to identify the listener class that corresponds to the JButton objects. This is referred to as registering the listener. We ll arbitrarily call that class the ButtonHandler that will be supporting the use of the calculate JButton and the exit JButton. We ll build upon the algorithm that we had established in the last exercise and identify those objects that we need to complete the program. For step 1. we ll need to include the instantiation of the object of type ButtonHandler. We ll also need to register the instance of this class with the JButton objects. Steps 2. and 3. will be separate classes of type ExitHandler and CalculateHandler, respectively, that we ll pseudo code below as well. 1. output the form and wait for the user to create a JButton event 2. input if the user clicks on the exit JButton (a) output to shut down the window 3. input if the user clicks on the calculate JButton (a) input the 3 String values from the JTextField objects that represent the assessed value, the regional school tax rate and the county tax rate (b) process to convert the 3 JTextField String objects to double 2

(c) process to calculate the regional school tax, county tax and total tax (d) output those three tax values in the appropriate JTextField objects Areas that need to be added from the previous exercise are displayed in blue. As was the case in that exercise, declarations and initializations (steps 0-3) are best declared within the PropertyTax6 class but before the PropertyTax6() constructor. The remaining code (steps 4-12) represent the body of the PropertyTax6() constructor. Lines that are displayed in blue represent areas where code needs to be written or modified to complete the assignement. 1. Pseudo code for Creating and Displaying the GUI Form Statement Data objects 0) declare & initialize an action listener object CalculateHandler & ExitHandler objects for each JButton 1) declare & initialize 6 labels JLabel, String and Swing.Constants objects 2) declare & initialize 6 text I/O fields JTextField & int objects 3) declare & initialize 2 button objects JButton & String objects 4) declare & initialize a Container Container object & getcontentpane() method 5) configure the Container Container.setLayout() method, GridLayout & int objects 6) place GUI objects in the Container JLabel, JTextField, JButton objects and Container.add() method 7) set the dimensions of the window setsize() method & int objects 8) set the title of the window settitle() method & String object 9) set the visibility of the window setvisible() method & boolean object 10) set the default close operation setdefaultcloseoperation() method & int objects 11) register the listener class for the exit JButton.addActionListener() method and JButton ExitHandler object 12) register the listener class for the JButton.addActionListener() method and calculate JButton CalculateHandler object When the user clicks on the exit JButton, we ll be executing the actionperformed() method of the ExitHandler class. This will simply invoke the System.exit(0) method. 2. Pseudo code for the exit JButton Event Statement Data objects 1) terminate the program and close the JFrame System.exit(0) method When the user clicks on the calculate JButton, we ll be executing the actionperformed() method of the CalculateHandler class. This will read the String values in the top 3 JTextFields, convert them to double for numeric computation and then display the results in the bottom 3 JTextFields. 3

3. Pseudo code for the calculate JButton Event Statement Data objects 1) convert assessed value to double JTextField.getText() and Double.parseDouble() methods & String and double objects 2) convert school tax rate to double JTextField.getText() and Double.parseDouble() methods & String and double objects 3) convert county tax rate to double JTextField.getText() and Double.parseDouble() methods & String and double objects 4) calculate school tax double objects 5) calculate county tax double objects 6) calculate total tax double objects 7) display school tax JTextField.setText() & String.format() methods & String and double objects 8) display county tax JTextField.setText() & String.format() methods & String and double objects 9) display total tax JTextField.setText() & String.format() methods & String and double objects Coding for Compilation Logon to your csc.oakton.edu account and create a new subdirectory of the labs directory called 6 to work on your assignment. cd labs mkdir 6 cd 6 You ll need to copy over your solution from the previous lab over to your local directory by issuing the following command. cp../5/propertytax5.java PropertyTax6.java emacs PropertyTax6.java & Given that we ve changed the file name, it will become necessary to change the name of the class as well as the name of the constructor. So, start your editing session by changing every occurrence of PropertyTax2 to PropertyTax6. In addition, to recognize events, we ll need to include the following import statements. import java.awt.*; import java.awt.event.*; Declaration of Variables By declaring our symbols for objects and constants within the class but outside of any methods, we are giving them what is referred to as class scope. This means that any line of code in the class can refer to the object. A more restrictive scope that is available is when the declaration occurs within a block that either defines a method or is embedded within the method of the class. Then, the symbol has what is referred to as block scope. This means that any line of code within the block can refer to the symbol. Declaring the objects in the manner that we have, (i.e. within the class, but outside of any method) means that we are giving these objects class scope and any method within the class can refer to them. 4

Follow the Pseudo Code for 1. Step 0 // declare and initialize an action listener object for each JButton CSC 156 - Assignment 6 PropertyTax We re going to implement the ExitHandler class before the Checkpoint and the CalculateHandler class after the Checkpoint. So, for now, we ll code the CalculateHandler reference as a comment. ExitHandler ebhandler = new ExitHandler(); // CalculateHandler cbhandler = new CalculateHandler(); Steps 1-10 // declare & initialize 6 labels // declare & initialize 6 text I/O fields // declare & initialize 2 button objects // declare & initialize a Container // configure the Container // place GUI objects in the Container // set the dimensions of the window // set the title of the window // set the visibility of the window // set the default close operation These steps were coded in the previous program and should simply be repeated. As was the case in the last exercise, steps 1 through 3 are best placed within the class but before the constructor. Steps 4 through 10 are best placed within the constructor. Steps 11-12 // register the listener class for the exit JButton // register the listener class for the calculate JButton Once again, we ll code the reference to the CalculateHandler class as a comment until we pass the Checkpoint. These would be the last lines coded within the constructor PropertyTax6(). exit.addactionlistener(ebhandler); // calculate.addactionlistener(cbhandler); Methods As we develop the remainder of this solution, we ll elaborate on methods and their features that we need to create comprehensive maintainable programs. Whenever we discuss a method in Java, there will always be some discussion on how it is invoked (or executed) and how it is implemented (or defined). The first method that we ll discuss is the newest one that we ve encountered. Constructor Methods Each object created with a class must have a means of instantiating or declaring it. Sometimes, there are options for initialization and other times there are default initialization that are available. The simplest type of invocation takes advantage of default initializations and conforms to the following format. class name symbolic name = new class name(); 5

The invocation of the constructor appears after the new operator. Essentially, a new instance of the class is created (or instantiated) and is assigned to the symbolic name for use within the program. The implementation of the constructor, like other methods, is defined within the class and follows the following format. Some classes provide multiple overloaded constructors that provide options for initialization that are distinguishable by the uniqueness of their parameter lists. In general, constructors do not have any return type, must have the same name as the class and should probably be identified with the keyword public so as to be invoked whenever necessary. // default constructor public class name( ) declarations; statement 1 ; statement 2 ;. statement m ; // constructor with initialization parameters public class name( data type 1 param 1,..., data type k param k ) declarations; statement 1 ; statement 2 ;. statement n ; void methods These and other methods do not rely upon the new operator. In most cases, they will be invoked by placing the method name on a statement by itself with however many arguments are necessary for the method to function correctly. The general format is as follows. method name(arg 1,..., arg k ); All arguments must be constants, variables or expressions. The definition or implementation of these types of methods have a general format that adheres to the following example. public static void method name( data type 1 param 1,..., data type k param k ) declarations; statement 1 ; statement 2 ;. statement n ; The primary example of such a method in our programs has been the main() method that each of our classes has used all along. In this particular program, the method looks as follows. 6

public static void main(string[] args) PropertyTax6 proptax = new PropertyTax6(); The main() method is the default method invoked in a Java application program that is executed on the command line by the java command. The String arguments can be input from the command line along with the name of the class file that contains the bytecode of the compiled program. Our main() method simply executes a constructor to generate an instance of class PropertyTax6 that is stored in proptax. Follow the Pseudo Code for 2. Step 1 // terminate the program and close the JFrame In order to implement the algorithm that we need for the exit JButton, we ll need to create the ExitHandler class and then implement the actionperformed() method, which is another void method, within that class. The ExitHandler class should be coded within the PropertyTax6 class, but outside of all other methods. public class ExitHandler implements ActionListener public void actionperformed(actionevent e) System.exit(0); Checkpoint Save your program to disk by choosing the Save command from the Files menu of your emacs session. Then, compile your program by choosing the Compile... command from the Tools menu and change the make -k that is displayed to javac PropertyTax6.java. Compiler errors can be parsed with the keystroke C-x and need to be repaired before your program can execute. When your program has compiled, click on your xterm window to access your command line prompt, and issue the command java PropertyTax6. The output displayed should look in the same manner as Figure 1, however clicking on the exit JButton should close the JFrame. Once you are sure that the you re on the right track, you should move on to implement the algorithm for the calculate JButton. Follow the Pseudo Code for 3. The class CalculateHandler should be coded identical to the class ExitHandler except for two instances. First of all, the lines within the actionperformed() method will be different and, of course, the name of the class should be different. Steps 1-3 // convert the assessed value to double // convert the school tax rate to double // convert the county tax rate to double You will need 3 variables that are declared within the actionperformed() method of type double for these assignments. Assuming that the JTextField containing the assessment information is named assesstf and that the double to contain this data is named assessd, the following declaration and initialization should be appropriate. 7

Figure 2: Lab 6 Sample Test Input double assessd = Double.parseDouble(assessTF.getText()); You will need two similar assignments to convert the tax rates. Steps 4-6 // calculate school tax // calculate county tax // calculate total taxes Three additional double variables would be useful to store these results. The tax rates should be divided by 100 before being multiplied by the assessed value. Code these 3 assignments before continuing. Step 7-9 // display the school tax // display the county tax // display the total taxes These are three more statements that simply take the double results of the previous 3 computations and display the values in the remaining 3 JTextField areas of the form. For example, if totaltaxd is the double field that contains the sum of the school and county taxes and if totaltaxtf is the JTextField of the form that is designed to display that result, then the following line would be appropriate for our interests. totaltaxtf.settext(""+ String.format("%.2f", totaltaxd)); You ll need to code two similar statements for the display of the calculated school and county taxes. Testing for errors At this point, your form should be fully functioning. Uncomment the lines that refer to the CalculateHandler class at Step 0 and Step 12. Recompile your program and execute it to display the image shown in Figure 1. Enter the data shown in Figure 2 and click on the calculate JButton. The display should now look like Figure 3. Moreover, each time that you change any of the top 3 JTextField areas and click on the calculate 8

Figure 3: Lab 6 Sample Test Output JButton, the results should be updated. Finally, the exit JButton should still be closing down your JFrame. There is a correctly function version of the program for PropertyTax6.java at this link. Printing and submitting Once you are satisfied with the correctness of your program, print it as you did with previous assignments by using the following command that assumes that you are working in the room 1234 at Oakton. Retrieve your copy from the printer. printer 1234 PropertyTax6.java Finally, submit your program with the following command that assumes that you are registered in section abc of CSC 156. submit csc156abc 6 9