Java, Swing, and Eclipse: The Calculator Lab.

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

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

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

Introduction to Eclipse

Part I: Learn Common Graphics Components

JFrame & JLabel. By Iqtidar Ali

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

MIT AITI Swing Event Model Lecture 17

Window Interfaces Using Swing Objects

This exam is closed textbook(s) and closed notes. Use of any electronic device (e.g., for computing and/or communicating) is NOT permitted.

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

Midterm assessment - MAKEUP Fall 2010

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

CS 251 Intermediate Programming GUIs: Components and Layout

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

To gain experience using GUI components and listeners.

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

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

PIC 20A GUI with swing

AP CS Unit 11: Graphics and Events

Window Interfaces Using Swing Objects

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

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

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

Dr. Hikmat A. M. AbdelJaber

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

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!

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

Swing/GUI Cheat Sheet

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

Java. GUI building with the AWT

CS108, Stanford Handout #22. Thread 3 GUI

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

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

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

Packages: Putting Classes Together

CSIS 10A Assignment 7 SOLUTIONS

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

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

FirstSwingFrame.java Page 1 of 1

GUI Forms and Events, Part II

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

Introduction. Introduction

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

Swing from A to Z Some Simple Components. Preface

Graphics User Defined Forms, Part I

Introduction to the JAVA UI classes Advanced HCI IAT351

Agenda. Container and Component

Java: Graphical User Interfaces (GUI)

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

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

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

SINGLE EVENT HANDLING

GUI Applications. Let s start with a simple Swing application in Java, and then we will look at the same application in Jython. See Listing 16-1.

Graphical User Interface

Swing: Building GUIs in Java

JFrame In Swing, a JFrame is similar to a window in your operating system

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

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

Programming Languages and Techniques (CIS120)

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

RAIK 183H Examination 2 Solution. November 11, 2013

Swing: Building GUIs in Java

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

Overview of Eclipse Lectures. Module Road Map

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

Chapter 12 Advanced GUIs and Graphics

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

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Swing - JLabel. Adding a text (and HTML) labels to a GUI

CHAPTER 2. Java Overview

Graphical User Interfaces. Comp 152

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

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

Getting Started with Eclipse/Java

H212 Introduction to Software Systems Honors

INTRODUCTION TO (GUIS)

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

Arrays, Exception Handling, Interfaces, Introduction To Swing

CS 180 Final Exam Review 12/(11, 12)/08

Systems Programming Graphical User Interfaces

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

SWING - GROUPLAYOUT CLASS

CS Exam 1 Review Suggestions

User interfaces and Swing

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

Points Missed on Page page 1 of 8

Adding Buttons to StyleOptions.java

Swing UI. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Building Graphical User Interfaces. GUI Principles

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

7. Program Frameworks

Top-Level Containers

CS 134 Programming Exercise 7:

Welcome to CIS 068! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) CIS 068

Final Examination Semester 2 / Year 2010

CS11 Java. Fall Lecture 4

Programmierpraktikum

Graphical User Interface (GUI)

Transcription:

Java, Swing, and Eclipse: The Calculator Lab. ENGI 5895. Winter 2014 January 13, 2014 1 A very simple application (SomeimageswerepreparedwithanearlierversionofEclipseandmaynotlookexactlyasthey would with the version you are using.) 1. Start Eclipse Ifyougeta workspacenotavailablemessage, clickok SettheworkspacetosomewhereontheH:drive. (Orifyouareusingyourowncomputer, wherever you like.) Notetheworkspacedirectory youwillneedtofinditlater. ClickOk. Closethe Welcome windowifthereisone. 2. Createanewproject(seeFig1) OntheMenuselect File/New/Project.... Select Java Project and click Next. Set Project Name to Calculator Set the execution environement to JavaSE-1.7. Select Create separate folders for source and class files Click Finish. (IfyougetamessagetotheeffectthatEGitcan tbefound,justclickok.ifthereis a further complaint, click OK again. 1

Inthe PackageExplorer view(ontheleftofthewindow)youshouldseeyourproject. 3. Createaclass(seeFig2) Right-click on the Calculator project in the Package Explorer Onthecontextmenuselect New/Class. Set Source folder to Calculator/src Set the Package to calculator. Setthe Name toview SetModifierstopublic Set Superclass to javax.swing.jframe(click Browse and then type the full class name.) Check checkboxes public static void main(string[] args) and Generate comments ClickonFinish. 4. Edittheimportdeclarationtobe import javax.swing.*; import java.awt.*; 5. Add a 0-parameter private constructor for View: In the constructor for View call setsize(300,300), setvisible( true) and setdefaultclose- Operation(JFrame.EXIT_ON_CLOSE) Your constructor should look like this privateview(){ setsize(300,300); setvisible( true); setdefaultcloseoperation(jframe.exit_on_close); } 6. mainisabitcomplicated(andstrange). Itshouldlooklikethis: public static void main(string[] args){ 2

} SwingUtilities.invokeLater( new Runnable(){ public void run(){ newview(); }}); 7. Runtheprogram(seeFig3) Save the file with control-s(on Macs: command-s) Check that there are no errors. (Errors will be indicated by red Xs in the Package Explorer.) InthePackageExplorer,rightclickonthefileView.java. Onthepopupcontextmenu,select RunAs/JavaApplication Youshouldseetheframeandshouldbeabletocloseit. 2 AddingaModel 1. Obtainthe Model.java file andthe Op.javafilefromthe course swebsite andsave them both to the Calculator/src/calculator directory with the workspace directory. 2. In the Package Explorer, right click on the Calculator project and select Refresh. The two new files should appear in the Package Explorer. 3. Open the Model class in the editor. Identify its public methods. 4. OpenEclipse soutlineviewbyselectingonthemenuwindow/showview/outline. The public methods are indicated in the Outline view by green circles. 5. TotheViewclassaddaninitializedprivatefield 3 Adding some components In the constructor for View: private final Model model = new Model(); 1. SetthelayoutmanagerfortheViewbyadding asthefirstlineoftheconstructor. setlayout(new FlowLayout()); 2. Add(afterthecalltosetLayout)codetoadd10buttonstotheView,labeled0to9. Iadded each button with code JButton digitbutton = new JButton( Integer.toString(i)); add( digitbutton); 3

3. Alsoaddabuttonlabeled +,abuttonlabelled Clear,andabuttonlabelled =. 4. Declare a private final field of type JLabel. Call it valuelabel. Initialize this field by creating a new JLabel. 5. Intheconstructoraddthevaluelabeltotheframe. 6. CreateanewmethodinView voidrefresh(){ valuelabel.settext( model.getresult());} 7. AddacalltorefreshasthefinalcommandinView sconstructor. 8. Try running your application. See Fig. 4 4 Closingtheloop Create a class DigitListener that implements the interface java.awt.event.actionlistener. Each DigitListenershouldknowaViewandaModel. (I.e. itshouldhavepointerstoaviewandtoamodel as its fields.) The constructor of DigitListener should record a pointer to a View, a pointer to a Model, and an int. Since DigitListener implements ActionListener, it must have a subroutine with signature @Override public void actionperformed( ActionEvent e) This subroutine should update the model by calling digit and then refresh the view. (Note that although the parameter is not used, it must still be declared.) Back in View s constructor you need to create instances of DigitListener and associate them with the appropriate listener like this. JButton digitbutton = new JButton( Integer.toString(i)); digitbutton.addactionlistener( new DigitListener( this, model, i)); add( digitbutton); Tryyourapplicationnow. Clickonthedigitbuttons. Youshouldseetheeffectintheoperand label. Notice how the Swing framework is calling your code even though the dependence goes the other way. This is an example of inversion of dependence. Create a class OperationListener similar to DigitListener, but that calls method operation rather thandigitinthemodel. NotethattheoperationmethodofclassModeltakesaparameterofthe enumerationclassop. TheOpclassdefinesanumberofconstantsoftypeOp. Torefertothese, you simply write Op.ADD or Op.CLEAR etc. Associate an OperationListener with the + button, the Clear button, and the = Figure5showsyourapplicationatthispointasaUMLclassdiagram. Try your application now. 4

5 Moretotry Try adding one button for each operation. Try changing the style of the buttons. Try adding moreoperationstothemodel. Seeifyoucanaddbuttonstochangetheprecisionorthebase. If you prefer RPN, create an RPN calculator. Make the calculator programmable. Obviously there is much more to learn about layout of components within containers. Try using GridLayout or GridBagLayout and also using JPanels and borders. 5

Figure 1: 6

Figure 2: 7

Figure 3: Figure 4: 8

Figure 5: 9