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

Similar documents
Graphical User Interfaces. Swing. Jose Jesus García Rueda

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

Introduction. Introduction

Window Interfaces Using Swing Objects

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions.

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

Agenda. Container and Component

Systems Programming Graphical User Interfaces

Window Interfaces Using Swing Objects

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Building Graphical User Interfaces. Overview

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

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

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

Graphical User Interfaces. Comp 152

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling

Part I: Learn Common Graphics Components

CSC 161 SPRING 17 LAB 2-1 BORDERLAYOUT, GRIDLAYOUT, AND EVENT HANDLING

Building Graphical User Interfaces. GUI Principles

State Application Using MVC

Window Interfaces Using Swing. Chapter 12

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

CSIS 10A Assignment 7 SOLUTIONS

Graphic User Interfaces. - GUI concepts - Swing - AWT

Dr. Hikmat A. M. AbdelJaber

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!

Java. GUI building with the AWT

JAVA NOTES GRAPHICAL USER INTERFACES

Introduction to the JAVA UI classes Advanced HCI IAT351

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

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

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

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

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

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

China Jiliang University Java. Programming in Java. Java Swing Programming. Java Web Applications, Helmut Dispert

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

H212 Introduction to Software Systems Honors

Client-side GUI. A simple Swing-gui for searching for proudcts

Graphical User Interfaces

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

User interfaces and Swing

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

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

Original GUIs. IntroGUI 1

ITEC 120 4/14/11. Review. Need. Objectives. GUI basics JFrame JPanel JLabel, JButton, JTextField Layout managers. Lecture 38 GUI Interactivity

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

TTTK Program Design and Problem Solving Tutorial 3 (GUI & Event Handlings)

Graphical User Interfaces (GUIs)

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

CS 134 Programming Exercise 7:

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

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

AP CS Unit 11: Graphics and Events

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

Chapter 13 Lab Advanced GUI Applications

MIT AITI Swing Event Model Lecture 17

CS 2113 Software Engineering

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

To gain experience using GUI components and listeners.

CHAPTER 2. Java Overview

Java Programming Lecture 6

Using Several Components

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM503 Programming B. Peter Schneider-Kamp.

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

Programming Languages and Techniques (CIS120)

CMP-326 Exam 2 Spring 2018 Solutions Question 1. Version 1. Version 2

Building Java Programs Bonus Slides

SINGLE EVENT HANDLING

JLayeredPane. Depth Constants in JLayeredPane

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

1005ICT Object Oriented Programming Lecture Notes

Together, the appearance and how user interacts with the program are known as the program look and feel.

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

GUI in Java TalentHome Solutions

BASICS OF GRAPHICAL APPS

Programming Exercise. Scribbler

Chapter 7: A First Look at GUI Applications

2110: GUIS: Graphical User Interfaces

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

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

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

Example: Building a Java GUI

Graphical User Interfaces in Java - SWING

News and info. Array. Feedback. Lab 4 is due this week. It should be easy to change the size of the game grid.

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

Example: Building a Java GUI

What Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { }

CMP 326 Midterm Fall 2015

COMP16121 Sample Code Lecture 1

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

GUI Forms and Events, Part II

JAVA NOTES GRAPHICAL USER INTERFACES

Theory Test 3A. University of Cape Town ~ Department of Computer Science. Computer Science 1016S ~ For Official Use

Queen s University Faculty of Arts and Science School of Computing CISC 124 Final Examination December 2004 Instructor: M. Lamb

RAIK 183H Examination 2 Solution. November 10, 2014

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

Swing Programming Example Number 2

Transcription:

A Calculator Project This will be our first exposure to building a Graphical User Interface (GUI) in Java The functions of the calculator are self-evident The Calculator class creates a UserInterface Class and a CalcEngine Class We will learn how to create objects such as Buttons and respond to the event that the button was pressed

* The main class of a simple calculator. Create one of these and you'll * get the calculator on screen. * @author David J. Barnes and Michael Kolling * @version 31 July 2000 public class Calculator private CalcEngine engine; private UserInterface gui; * Create a new calculator and show it. public Calculator() engine = new CalcEngine(); gui = new UserInterface(engine); Calculator Class * In case the window was closed, show it again. public void show() gui.setvisible(true);

Highlights of Building a GUI - 1 The Layout Components The outer component is a Jframe A Jpanel has a border layout has five areas: NORTH, EAST, SOUTH, WEST, and CENTER The buttons on the calculator are arranged in a 4x4 grid layout Objects placed in the layout The display of the numeric value is a JTextField The buttons are, not surprisingly, JButton objects The message at the bottom is a JLabel

Highlights of Building a GUI - 2 Each Button has an actionlistener attached to it; the events listen for button presses actionperformed uses the button label to separate out button presses and handles each button press accordingly Think ahead and try to predict how each of these button presses will be handled Buttons 0..9 Buttons + and The = Button The C (clear) button The? Button

import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class UserInterface implements ActionListener private CalcEngine calc; private boolean showingauthor; private JFrame frame; private JTextField display; private JLabel status; The GUI - 1 * Create a user interface for a given calcengine. public UserInterface(CalcEngine engine) calc = engine; showingauthor = true; makeframe(); frame.setvisible(true); // methods go here

* Make this interface visible again. (Has no effect if it is already * visible.) public void setvisible(boolean visible) frame.setvisible(visible); * Make the frame for the user interface. private void makeframe() frame = new JFrame(calc.getTitle()); JPanel contentpane = (JPanel)frame.getContentPane(); contentpane.setlayout(new BorderLayout(8, 8)); contentpane.setborder(new EmptyBorder( 10, 10, 10, 10)); display = new JTextField(); contentpane.add(display, BorderLayout.NORTH); JPanel buttonpanel = new JPanel(new GridLayout(4, 4)); addbutton(buttonpanel, "7"); addbutton(buttonpanel, "8"); addbutton(buttonpanel, "9"); addbutton(buttonpanel, "C"); The GUI - 2

addbutton(buttonpanel, "4"); addbutton(buttonpanel, "5"); addbutton(buttonpanel, "6"); addbutton(buttonpanel, "?"); addbutton(buttonpanel, "1"); addbutton(buttonpanel, "2"); addbutton(buttonpanel, "3"); buttonpanel.add(new JLabel(" ")); addbutton(buttonpanel, "0"); addbutton(buttonpanel, "+"); addbutton(buttonpanel, "-"); addbutton(buttonpanel, "="); The GUI - 3 contentpane.add(buttonpanel, BorderLayout.CENTER); status = new JLabel(calc.getAuthor()); contentpane.add(status, BorderLayout.SOUTH); frame.pack(); private void addbutton(container panel, String buttontext) JButton button = new JButton(buttonText); button.addactionlistener(this); panel.add(button);

public void actionperformed(actionevent event) String command = event.getactioncommand(); if(command.equals("0") command.equals("1") command.equals("2") command.equals("3") command.equals("4") command.equals("5") command.equals("6") command.equals("7") command.equals("8") command.equals("9")) int number = Integer.parseInt(command); calc.numberpressed(number); else if(command.equals("+")) calc.plus(); else if(command.equals("-")) calc.minus(); else if(command.equals("=")) calc.equals(); else if(command.equals("c")) calc.clear(); else if(command.equals("?")) showinfo(); redisplay(); The GUI - 4

* Update the interface display to show the current value of the * calculator. private void redisplay() display.settext("" + calc.getdisplayvalue()); * Toggle the info display in the calculator's status area between the * author and version information. private void showinfo() if(showingauthor) status.settext(calc.getversion()); else status.settext(calc.getauthor()); showingauthor =!showingauthor; The GUI - 5

The Event Handlers - 1 The model of a calculation Numeric operations have the form <leftoperand> <operation> <lastoperand> We have to remember the leftoperand and the operation while the lastoperand is fetched The value that is displayed is held in displayvalue Now be very specific What happens when a digit key is pressed?

Buttons + and The Event Handlers 2 The = button (this takes some thought) The C (clear) button A question: how is a chain calculation, such as 2 + 3 + 4 + 5 =, handled?

* The main part of the calculator doing the calculations. * @author David J. Barnes and Michael Kolling * @version 1.0 public class CalcEngine // The calculator's state is maintained in three fields: // buildingdisplayvalue, haveleftoperand, and lastoperator. // Are we already building a value in the display, or will the // next digit be the first of a new one? private boolean buildingdisplayvalue; // Has a left operand already been entered (or calculated)? private boolean haveleftoperand; // The most recent operator that was entered. private char lastoperator; // The current value (to be) shown in the display. private int displayvalue; // The value of an existing left operand. private int leftoperand; * Create a CalcEngine instance. public CalcEngine() clear(); // methods go here Calculator Engine - 1

* Return the value that should currently be displayed * on the calculator display. public int getdisplayvalue() return displayvalue; * A number button was pressed. * Either start a new operand, or incorporate this number as * the least significant digit of an existing one. public void numberpressed(int number) if(buildingdisplayvalue) // Incorporate this digit. displayvalue = displayvalue*10 + number; else // Start building a new number. displayvalue = number; buildingdisplayvalue = true; Calculator Engine - 2

* The 'plus' button was pressed. public void plus() applyoperator('+'); * The 'minus' button was pressed. public void minus() applyoperator('-'); Calculator Engine - 3 * The '=' button was pressed. public void equals() // This should completes the building of a second operand, // so ensure that we really have a left operand, an operator // and a right operand. if(haveleftoperand && lastoperator!= '?' && buildingdisplayvalue) calculateresult(); lastoperator = '?'; buildingdisplayvalue = false; else keysequenceerror();

* The 'C' (clear) button was pressed. * Reset everything to a starting state. public void clear() lastoperator = '?'; haveleftoperand = false; buildingdisplayvalue = false; displayvalue = 0; Calculator Engine - 4 * Return the title of this calculation engine. public String gettitle() return "Java Calculator"; * Return the author of this engine. public String getauthor() return "David J. Barnes and Michael Kolling";

public String getversion() return "Version 1.0"; * Combine leftoperand, lastoperator, and the * current display value. * The result becomes both the leftoperand and * the new display value. private void calculateresult() switch(lastoperator) case '+': displayvalue = leftoperand + displayvalue; haveleftoperand = true; leftoperand = displayvalue; break; case '-': displayvalue = leftoperand - displayvalue; haveleftoperand = true; leftoperand = displayvalue; break; default: keysequenceerror(); break; Calculator Engine - 5

* Apply the given operator. private void applyoperator(char operator) // If we are not in the process of building a new operator // then it is an error, unless we have just calculated a // result using '='. if(!buildingdisplayvalue &&!(haveleftoperand && lastoperator == '?')) keysequenceerror(); return; if(lastoperator!= '?') // First apply the previous operator. calculateresult(); else // The displayvalue now becomes the left operand of this // new operator. haveleftoperand = true; leftoperand = displayvalue; lastoperator = operator; buildingdisplayvalue = false; Calculator Engine - 6

* Report an error in the sequence of keys that was pressed. private void keysequenceerror() System.out.println("A key sequence error has occurred."); // Reset everything. clear(); Calculator Engine 7

Lab 15 A Binary Calculator Binary numerals only contain digits 0 and 1 so there are only two digit buttons There is only one operation, +, and the equal key to complete a calculation What differs most from the previous calculator is that there are two types of clear: CA (clear all) resets all fields to start an entire new calculation C (clear) only resets the current operand, any left operand and operation are retained

Binary Addition The basic operations 0 + 0 = 0, 0 + 1 = 1, 1 + 0 = 1, 1 + 1 = 10 this mean 0 and carry 1 to the left Examples, with the decimal values at the right 1 0 1 1 0 1 (45) + 1 0 1 1 0 (22) 1 0 0 0 0 1 1 (67) 1 1 1 1 1 1 (63) + 1 1 1 1 1 (31) 1 0 1 1 1 1 0 (94)