Java Programming Lecture 6

Similar documents
Java Programming Lecture 7

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!

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

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

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects

1.00 Lecture 14. Lecture Preview

Graphic User Interfaces. - GUI concepts - Swing - AWT

Class 14: Introduction to the Swing Toolkit

Graphical User Interfaces. Comp 152

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

Chapter 12 GUI Basics

Graphical User Interface (GUI)

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

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

To gain experience using GUI components and listeners.

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Chapter 12 Advanced GUIs and Graphics

Lecture 5: Java Graphics

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

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI

Java - Applets. public class Buttons extends Applet implements ActionListener

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

Introduction to the JAVA UI classes Advanced HCI IAT351

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

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

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

Assignment 2. Application Development

Unit 6: Graphical User Interface

Programming graphics

Graphics and Painting

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

Today. cisc3120-fall2012-parsons-lectiii.3 2

Contents Chapter 1 Introduction to Programming and the Java Language

CS 251 Intermediate Programming GUIs: Components and Layout

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

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

Sri Vidya College of Engineering & Technology

+! Today. Lecture 3: ArrayList & Standard Java Graphics 1/26/14! n Reading. n Objectives. n Reminders. n Standard Java Graphics (on course webpage)

Part I: Learn Common Graphics Components

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

Introduction. Introduction

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

Java Swing. Lists Trees Tables Styled Text Components Progress Indicators Component Organizers

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

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,

2110: GUIS: Graphical User Interfaces

2IS45 Programming

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

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

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

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

AP CS Unit 11: Graphics and Events

Window Interfaces Using Swing. Chapter 12

Lecture 3: Java Graphics & Events

Graphical User Interfaces

Graphics User Defined Forms, Part I

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

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

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

CS Fall Homework 5 p. 1. CS Homework 5

Packages: Putting Classes Together

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

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

Agenda. Container and Component

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

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

CS11 Java. Fall Lecture 3

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

Java. GUI building with the AWT

Lecture 18 Java Graphics and GUIs

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

PIC 20A GUI with swing

Graphical User Interface (GUI)

We are on the GUI fast track path

Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

CS Problem Solving and Object-Oriented Programming

CS11 Java. Fall Lecture 4

CSE Lab 8 Assignment Note: This is the last lab for CSE 1341

Systems Programming Graphical User Interfaces

Unit 7: Event driven programming

Java Applets This is not a Java course! (You re supposed to know about Java.)

JAVA. A. Zakiuddin Ahmed. M.Sc.,M.Phil M.S.(Edn), PGDCSM, Professor in Computer Science, P. Rizwan Ahmed. MCA., M.Sc.,M.A., M.Phil.

Lab & Assignment 1. Lecture 3: ArrayList & Standard Java Graphics. Random Number Generator. Read Lab & Assignment Before Lab Wednesday!

Graphical User Interface (GUI) and Object- Oriented Design (OOD)

H212 Introduction to Software Systems Honors

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing

Chapter 2 First Java Programs

CST141 Thinking in Objects Page 1

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

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

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

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

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

SELF-STUDY. Glossary

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

Graphical User Interface (GUI)

CSE 331 Software Design & Implementation

Transcription:

Java Programming Lecture 6 Alice E. Fischer Feb 15, 2013 Java Programming - L6... 1/32

Dialog Boxes Class Derivation The First Swing Programs: Snow and Moving The Second Swing Program: Smile Swing Components Using Swing Components Summary and Homework Java Programming - L6... 2/32

Dialog Boxes Output Dialog Boxes Parsing the Input String Example: Popup Java Programming - L6... 3/32

Input Dialog Boxes String s = JOptionPane.showInputDialog ( ".."); We call the showinputdialog() function of the class JOptionPane class and supply the message that the dialog box will display. A dialog box pops up in the center of the screen. It displays our message, followed by a white area in which the user is supposed to type an input. This input is delivered to your program in the form of a string, not a number. Java Programming - L6... 4/32

Output Dialog Boxes JOptionPane.showMessageDialog (null, "..."); We call the showmessagedialog() function of the class JOptionPane class and supply the message that the dialog box will display. A dialog box pops up in the center of the screen. It displays our message. The form and contents of this window are the default style for JOptionPane. To close the window, press the OK button. Java Programming - L6... 5/32

Parsing the Input String When we use a Scanner, it parses the input stream for us, and handles number conversion and input errors. If you use a dialog box, however, this work must be done by your own code. It is like reinventing the wheel. Java had dialog boxes many years ago. Many people complained about Java being a primitive language, unsuitable for beginners. The Scanner class was introduced in Java 5. An input dialog box delivers the input to your program in the form of a string. Use parseint() to analyze the string and do the ASCII-to-integer conversion. It will throw an exception if the string is not a legal integer. Java Programming - L6... 6/32

Purpose of Derivation Class derivation is used in Java and other OO languages for several purposes: Hooking into the power of a pre-existing system like Swing: your program 6. Polymorphic data: A basic data class, with variations. Demo: Jack-O-Lantern Reusable code: The existing class is almost what you want, but not quite. We will see this when we get to adapter classes. Java Programming - L6... 7/32

What is Derivation? A new class is defined by saying what it has or does that is slightly different from an existing class. The keyword is extends The existing class is the base class, or superclass. The new class is the derived class or subclass. A subclass object has ALL the properties of the original class, plus those it defines. Even though the subclass object HAS those members, private members of the base class are not visible to it. When you create a class that is intended as a base class, you often declare some of its members to be protected. Protected members are visible to derived classes but are otherwise like private members. Java Programming - L6... 8/32

Derivation Example Suppose you are writing a payroll program for a company with three kinds of employees: Salaried, Hourly, and Contractor. Employee would be the base class, with these members, inherited by all subclasses: Name, payrate, and other basic info. A constructor and tostring function. A pay() function that does basic operations common to all employees. The Salaried class would extend Employee and add one member: A pay() function that uses the right formula for salaried employees. An hourly employee would have additional members to deal with overtime, and another method for tostring(). Java Programming - L6... 9/32

Derived Classes Inherit Members This is a polymorphic data class. base class derived class Employee Salaried employee Hourly employee name payrate name payrate Contractor hoursworked Salaried Hourly Java Programming - L6... 10/32

Using a Pre-existing System Class derivation is used in Java to allow users to use Swing without understanding it or being able to create it. We start by extending JFrame and giving it a layout. We then add panels or objects derived from the Panel class. Widgets and artwork go inside the panels. Everything we use in a Swing window is either An instance of a predefined Java class. An instance of a class derived from a predefined Java class. When we make window applications, we are always dealing with something we can t see and don t fully understand. We do it by learning a few simple rules! Java Programming - L6... 11/32

Deriving from JFrame Swing JFrame can contain JPanel Lantern can contain Canvas Canvas3 Canvas2 Canvas4 Java Programming - L6... 12/32

Why do we need Derivation? We use Java s GUI libraries by extending the pre-defined classes. To make an application with a window, we extend JFrame To put buttons or dialog boxes in part of the window, we extend JPanel Java is organized this way so that we can use the windowing toolkit without understanding (or even seeing) all the complex things that are inside it. When we make window applications, we are always dealing with something we can t see and don t fully understand. We do it by learning a few simple rules! Java Programming - L6... 13/32

The First Swing Programs Snow: JFrames, windows, fonts, color. Moving: JFrames, windows, fonts, color, size and position. Window events. Smile: RGB colors, button events. Java Programming - L6... 14/32

Moving What is going on here? The number increases whenever the window is repainted. The window is repainted when it is resized. The system does window management, but calls the application s paint() function as part of the process of repainting the window. The window is repainted when you minimize it and when you expand it again. Nothing happens when you move or click the mouse, unless you are resizing the window. Nothing happens when you move the window without resizing. Java Programming - L6... 15/32

How Moving Works When you resize the window, That generates an event. The event is handled (like an exception is handled) in the event thread. The proper handler (in this case, the default) for this kind of event is called and runs. It calls your paint function, which calls the JFrame s paint function. You see the screen repainted. Java Programming - L6... 16/32

Creating Colors The Colors class is in the package java.awt. The predefined Colors are black, blue, cyan, darkgray, gray, green, lightgray, magenta, orange, pink, red, white, yellow. UPPER CASE also works: BLACK, BLUE, DARK_GRAY, LIGHT_GRAY, YELLOW, etc. You can and should create your own colors. Color lilac = new Color (100, 100, 200); Colors are specified in the RGB coordinate system (0, 0, 0) is black. (128, 128, 128) is medium gray. (255, 255, 255) is white. Java Programming - L6... 17/32

Creating Fonts You can and should create your own fonts. Font myfont = new Font("serif", Font.BOLD+Font.ITALIC, 24); Choose style, face, and size: Serif (with hats and shoes), SansSerif (bare) and Monospaced (fixed-width) Alternative names are: Times, Helvetica and Arial, Courier. Choose any reasonable size. Bold, plain, italic or bold-italic. The default font is SansSerif, Plain, size 12. Java Programming - L6... 18/32

Using Fonts Use the setfont and setcolor functions: g.setfont(myfont); g.setcolor(color.magenta); When you draw a string, it will be displayed in the current font and color, and at the given (x,y) screen coordinates. g.drawstring(message, 0, 36); Java Programming - L6... 19/32

The Second Swing Program: Smile JFrames, JPanels, and the graphics window Widgets: JButton, JLabel, JTextbox The placement of widgets in panels. Layouts Shapes: Rectangle, Oval Java Programming - L6... 20/32

Swing Components Application vs. Applet An application has a main function. An applet does not it has an init() function instead. An application runs in an IDE or in a command window. An applet is run by running an.html file in a browser. Some IDEs make it easy to test applets, others don t. In a graphics application, the main function must create a new object that extends JFrame.. Smile S = new Smile(); It is helpful to set the window closing operation, also: S.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Java Programming - L6... 21/32

Swing Components Frames and Panels The main Swing window is a JFrame. It wraps, organizes, and controls a set of panels within it. You can put JPanels inside the JFrame to hold and organize other widgets. One frame may have many JPanels. They are arranged according to a layout. JPanels also have layouts, which are used to organize the smaller panels within. For a JFrame, the default layout is BorderLayout. Java Programming - L6... 22/32

Swing Components Layouts Elements are placed into a JFrame or JPanel according to its current layout. The simplest layouts are: BorderLayout: Panels can go on any edge or in the center. Positions are called North, South, East, West, and Center, and can be written two ways: BorderLayout.NORTH or "North". FlowLayout: Add elements left to right until the width is filled, then start another line. GridLayout( r, c): A matrix with r rows and c columns, which is filled left to right and top to bottom. There are many other layouts, with tabs, cards, and much more. Java Programming - L6... 23/32

Swing Components Widgets A widget is an element, large or small, complex or simple, that you might put into a graphics window. The basic Swing widgets are: JPanel: A container to organize other widgets. JButton: Click it to cause some action. JTextField: a box into which the user can enter input. JLabel: The label for a text field. JTextArea: A big output box able to hold several lines of data. JCheckBox: a box for entering a boolean off/on input. JRadioButton: one of a set of mutually-exclusive off/on elements. These are organized into ButtonGroups. Java Programming - L6... 24/32

Using Swing Components To Create a JFrame In your main() function: 1. Declare and create the app window: Smile s = new Smile(); 2. Set the app to terminate when the window is closed: s.setdefaultcloseoperation(jframe.exit_on_close); Java Programming - L6... 25/32

Using Swing Components To Customize and Use your JFrame In your JFrame-class constructor: 1. Give the window a title: super("smile"); 2. Control its position and size: setbounds( x, y, width, height); 3. Grab the graphics area: Container pane = getcontentpane(); 4. Change the layout if you don t want a BorderLayout. 5. Add components to the graphics area: pane.add(p1, "North"); 6. Make the window visible: setvisible(true); Java Programming - L6... 26/32

Using Swing Components To Use a Panel 1. Declare and create it: private JPanel p1 = newjpanel(); 2. Give it a layout: p1.setlayout( new GridLayout(1, 2)); 3. Add widgets to it: p1.add(red); p1.add(rlabel); 4. Put your panel into the JFrame object named pane: pane.add(p1, "North") or pane.add(p1, BorderLayout.NORTH) Java Programming - L6... 27/32

Using Swing Components To Use a Text Field Text fields can be used for input and output. 1. Declare it, name it, and supply an initial value for the display. The second parameter is the minimum width of the box. private JTextField red = new JTextField("0", 5); 2. Create a label for it: private JLabel rlabel = new JLabel("red"); 3. Add both to a panel so that one is next to or above the other: p1.add(red); p1.add(rlabel); Java Programming - L6... 28/32

Using Swing Components To Make a Clickable Button 1. Declare it, name it, and supply a label for the display: private JButton submit = new JButton ("submit") 2. Add it to a panel : p5.add(submit); 3. Register the button so that Swing will listen for button events: submit.addactionlistener(this); 4. Define a handler for these events: public void actionperformed(actionevent event) { Object source = event.getsource(); if (source == submit){...} } Java Programming - L6... 29/32

Using Swing Components A Button Handler 1. Declare that your class implements the ActionListener interface: class Smile extends JFrame implements ActionListener { 2. Define the method : public void actionperformed(actionevent event) { 3. Grab the event information: Object source = event.getsource(); 4. Use if...else to identify which button was clicked: if (source == submit) {...} 5. Download information from relevant TextFields and use that info to modify your model: rd = new Integer (red.gettext()).intvalue(); 6. Do other appropriate actions for that button and repaint the window: repaint(); Java Programming - L6... 30/32

Java Summary We have discussed the following packages, classes, methods, and concepts today: try, catch, finally, throw getmessage(), getcause(), printstacktrace(), System.exit(0) Dialog boxes for input and output The concept of derivation and extends, super Font and setfont() RGB colors, Color(), and setcolor() Screen coordinates and drawstring() The paint() function Java Programming - L6... 31/32

Homework This Week Read Chapter 12: GUI Basics P6. Hello Swing! Due Friday, February 24. Write a simple Swing program, using Moving as an example. Create three fonts (different sizes and styles) and two new colors. Use these with one pre-defined color to display your full name three times on the screen in non-overlapping places, and at random-looking coordinates. Give a title to your JFrame window. Be sure the main thread terminates when you close the window. Hand in your code (one class) and a screen shot of your output. Java Programming - L6... 32/32