cs1371 introduction to computing for engineers l.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
CS1371 Introduction to Computing for Engineers PowerPoint Presentation
Download Presentation
CS1371 Introduction to Computing for Engineers

Loading in 2 Seconds...

play fullscreen
1 / 83

CS1371 Introduction to Computing for Engineers - PowerPoint PPT Presentation


  • 289 Views
  • Uploaded on

CS1371 Introduction to Computing for Engineers Basic Graphics Basic Graphics Graphics Principles Containers Components Layouts Events Learning Objectives Basics of Java Graphics Objective (demo Graphic4) Background

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

CS1371 Introduction to Computing for Engineers


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
basic graphics
Basic Graphics

Graphics Principles

  • Containers
  • Components
  • Layouts
  • Events

Learning Objectives

Basics of Java Graphics

objective
Objective

(demo Graphic4)

background
Background
  • As we have already seen, printing to, and reading from, a text window is pretty ugly.
    • Java is not intended for text I/O
  • This module is all about what Java was designed for: graphical window interaction
    • So this should be really easy, right?
  • Well, everything is relative. Java graphics are much easier than, for example, C++.
  • Moreover, they are completely portable between computers.
    • If your program runs on your computer, it will run on anything with the same or later release of the Java Virtual Machine (JVM)
agenda
Agenda

Graphical User Interfaces

-- overview

-- essential elements

Containers

-- overview

-- composition vs. inheritance

Components

-- examples

Layout Managers

-- examples

Our Roadmap

agenda6
Agenda

Graphical User Interfaces

-- overview

-- essential elements

Containers

-- overview

-- composition vs. inheritance

Components

-- examples

Layout Managers

-- examples

Our Roadmap

graphical user interface

Downloading libcrypt ...

Enter

Edit

File

40%

Cancel

Open

Save

Save As...

Quit

Graphical User Interface
  • A Graphical User Interface (GUI) is one variety of user interface. .
  • User interacts with objects on the screen (icons, buttons, scroll-bars, etc.) via mouse clicks or keyboard actions.

Ok

gui popularity
GUI Popularity
  • Popularized in 1980s by the Macintosh.
    • Now state of the practice, and not final word in UI
    • Intended to replace text-based "command line" and "function key" interfaces.
    • Despite similarities, GUIs are typically platform-specific (Windows 95/98/NT/1900, MacOS, X Windows look-and-feel standards).
    • Some graphical toolkits now provide cross-platform APIs. E.g. wxWindows, GTK+, Java.
java s gui capabilities

1.

2.

Java’s GUI Capabilities

Java provides essentially two related toolkits for making GUIs:

The Abstract Windowing Toolkit ("AWT"), and

The Java Foundation Classes ("Swing")

Swing is merely an expanded version of the AWT,

and provides greater control and convenience.

why two toolkits in java
Why Two Toolkits in Java?

MFC

AWT, then

JFC or "Swing"

Well, it’s a long story. In short, JFC (swing) is Sun’s answer to Microsoft’s MFC--a detailed toolkit library.

cautionary note

Button

JButton

Cautionary Note
  • Java has two flavors of toolkits:
  • Swing and
  • AWT.
  • It is not wise to mix AWT and Swing Components.
  • For your first programs, stick with one toolkit or the other.
  • We’ll start off with AWT, and the switch to Swing Components.
  • How do you tell them apart?
  • Generally, but not always, Swing Components will have a
  • "J" in front of the class name:

AWT

Swing

keep in mind
Keep in Mind
  • We will program graphical elements in source code (text).
    • There are drag and drop systems but usually there is an underlying text-based system
    • Eventually you need to get down to the text level
  • Java is designed to work across different platforms.
    • This poses special challenges
  • As does the very nature of WIMP GUI’s (windows, icons, menus, and pointing device graphic user interface)
slide13

Steps to GUI Construction

We will learn GUI creation in two steps: the "view", and then the "controls" or event handling.

1.

  • In Java, to create a GUI, you (1):
    • Specify a Container, using . . .
    • a Layout Manager to . . .
    • place Components and/or Containers of Components . . . on the screen as desired.

I.e. UI form and

appearance

FIRST

LATER

2.

  • In Java, to make a GUI act as the
  • interface for a program, you (2)
    • Design human/computer dialog, using Listeners and component-generated events

I.e. UI interaction

and behavior

agenda14
Agenda

Graphical User Interfaces

-- overview

-- essential elements

Containers

-- overview

-- composition vs. inheritance

Components

-- examples

Layout Managers

-- examples

Our Roadmap

gui design creation

File Edit Help

CLICK ME

GUI Design & Creation

There are three essential constructs in any GUI:

Containers

-- used to hold items (e.g., the frame)

Components

-- the widgets or interactors (e.g., buttons)

LayoutManagers

-- the hidden algorithm used to organize the widgets inside the container

offset

offset

pop quiz hint

1.

Containers

File Edit Help

offset

2.

Components

CLICK ME

3.

LayoutManagers

offset

Pop Quiz (hint)

What are the three basic constructs

used in every GUI?

agenda17
Agenda

Graphical User Interfaces

-- overview

-- essential elements

Containers

-- overview

-- composition vs. inheritance

Components

-- examples

Layout Managers

-- examples

Our Roadmap

containers

Examples of Containers:

Swing

AWT

  • JPanel
  • JFrame
  • JApplet
  • JWindow
  • Panel
  • Frame
  • Applet
  • Window
Containers

STEP 1

Containers are special components that may contain other components.

Note: Containment is not the same as inheritance extension.

A Frame may contain buttons,

but buttons are not subclasses of Frame.

containers19
Containers
  • A Container is a class that extends from java.awt.Container
  • As it turns out, the class "Container" is itself a Component.
  • Containers can have:
      • Layouts set on them
      • Other components or containers added to them.

Object

Component

Container

example
Example

Let’s make a simple Frame.

When working with

GUIs, you often have to consult the API.

Note the inheritance structure of your classes.

example21
Example
  • So far, we’ve used the API to learn how to make a Frame.
  • We found constructors for:
      • public JFrame ();
      • public JFrame (String strTitle);
  • Now, how can we set the size of the Frame?
  • We again return to the API.
example22
Example

The class java.awt.Frame does not contain a method to set its size. But such a method was inherited from java.awt.Component:

example23
Example

Likewise, there’s no method in java.awt.Frame to make the Frame visible. Instead, we find the method "show()" was inherited from java.awt.Window

hello gui
Hello GUI

import java.awt.*;

public class HelloGUI {

public static void main (String[ ] arg) {

System.out.println

("About to make GUI");

Frame f = new Frame ("Hello GUI");

f.setSize( 200, 200 );

f.show();

System.out.println

("Finished making GUI");

} // main

} // class HelloGUI

notice anything odd
Notice anything odd?

When we reach the end of main (as our print statement indicates) why doesn’t the program end?

explanation

import javax.swing.*;

public class HelloGUI {

public static void main (String[ ] arg) {

System.out.println

("About to make GUI");

JFrame f = new JFrame ("Hello GUI");

f.setSize( 200, 200 );

f.show();

System.out.println

("Finished making GUI");

} // main

} // class HelloGUI

Explanation

When the Java VM created our JFrame, it entered into a kind of ‘infinite loop’,

waiting for input and

events. (This is common

of graphical toolkits.)

while(true){

//get user input

// handle event

}

agenda28
Agenda

Graphical User Interfaces

-- overview

-- essential elements

Containers

-- overview

-- composition vs. inheritance

Components

-- examples

Layout Managers

-- examples

Our Roadmap

design idea

1.

Inheritance

-- our class extends a container

2.

Composition

-- our class holds a container

Design Idea

We really have two choices when working with top-level containers:

java.awt.Frame

MyGUI

We will implement containers using composition

MyGUI

java.awt.Frame

example30

Check the API

Will call constructor,

so the show() method gets called

Example

import java.awt.*;

public class HelloComposition

{

Frame f;

public HelloComposition(){

f = new Frame("Composition Test");

f.setSize(200,200);

f.setBackground(Color.red);

f.show();

}

public static void main (String[] arg)

{

HelloComposition h = new HelloComposition();

}

}

container summary

myFrame.setBackground(Color.red);

An inherited

method

A class, also

in the API

Container Summary

Creating containers requires careful study of the API. Watch the inheritance structure of the classes.

A top-level container, like a Frame, requires event handlers (covered later).

There are many useful methods for customizing containers. Just look them up in the API. E.g.:

agenda32
Agenda

Graphical User Interfaces

-- overview

-- essential elements

Containers

-- overview

-- composition vs. inheritance

Components

-- examples

Layout Managers

-- examples

Our Roadmap

components
Components

STEP 2

  • Most interactionsin a Java GUI are with Components.
  • Another generic term for Component in other GUIs
  • (e.g. X Windows) is "widget".
  • Different types of components for different types of
  • interaction (e.g. buttons, etc.)
  • User interactions with components create events (thus, allow event-driven programming)
  • As a rule, a Component cannot have other components inside
    • Exceptions to rule: pop up menus may have menu items added to them. And Containers are themselves components due to inheritance.
component examples35

Recall:

A Container

"is a"

Component

Component Examples

Component - generic widget that you can interact with

Button - a widget that you can press

Canvas - a widget that you can draw on

Checkbox - a widget that is checked or not checked

Choice - an option menu that drops down

Container - a generic class that contains Components

Panel - a Container to be used inside another container; used to split an existing window

Label - a single line of read-only text

List - a list of Strings

Scrollbar - a horizontal or vertical scrollbar

TextComponent

TextArea - multi-line editable text

TextField - single-line editable text

slide36

Components--Examples

  • Canvas:
  • typically a drawing surface on which shapes, graphs, pictures, etc can be drawn.
  • utilize mouse events and mouse motion events to interact with the user to accomplish the drawing tasks.
  • TextField:
  • a one-line data entry area
  • theoretically infinite in length
  • can generate Key events to indicate that the user has typed a key
  • more typically, it generates an Action event when the user finishes the data entry and hits Return in the TextField.
slide37

Components--Examples

  • Button:
  • simply a clickable component
  • appears as a standard button on whatever graphical environment the user happens to be running at the time
  • generates an Action event when clicked
  • Label:
  • a one-line field of text.
  • user cannot change this text directly; program changes text with setText( ) method.
  • usually not used to capture events (but could)
  • usually used as a one-way information source to provide a message to the user.
joining components containers
Joining Components & Containers

Containers have a method:

public void add (Component c)

that allows us to place items inside. Thus:

Panel p = new Panel();

Button b1 = new Button ("Example 1");

Button b2 = new Button ("Example 2");

p.add(b1);

p.add(b2);

In this example, two buttons are added to the panel.

example39
Example

import java.awt.*;

public class HelloComponent

{

Frame f;

public HelloComponent(){

f = new Frame("Component Test");

f.setSize(200,200);

f.setBackground (Color.red);

Panel p = new Panel();

Button b = new Button ("Hello Components");

p.add(b);

f.add(p);

f.show();

}

public static void main (String[] arg)

{

new HelloComponent();

}

}

basic graphics ii
Basic Graphics II

Graphics Principles

  • Containers
  • Components
  • Layouts
  • Events

Learning Objectives

Basics of Java Graphics

objective44
Objective

(demo Graphic4)

agenda45
Agenda

Graphical User Interfaces

-- overview

-- essential elements

Containers

-- overview

-- composition vs. inheritance

Components

-- examples

Layout Managers

-- examples

Our Roadmap

layout managers
Layout Managers

STEP 3

We can now create Components and Containers.

But how can they be organized? We might be tempted to call methods that set the x, y location of a component in a container.

Consulting the API, we find some likely methods:

public void setLocation(int x, int y);

public void setSize(int width, int height);

slide47

75 pixels down

Click

25 pixels over

Layout Managers -- Motivation

  • To arrange items, one could specify the location of a Component by specific x and y coordinates. The Component class contains the method setLocation(int width, int height):
    • Frame f = new Frame();
    • f.setSize(500,500);
    • Button myButton = new Button ("Click");
    • add(myButton);
    • myButton.setLocation(25, 75);

NOTE:

Origin 0,0

at top left

What’s

wrong

with this

approach?

Note: Button’s

x and y coordinate

starts from top left

slide48

Layout Managers -- Motivation

  • Problems with specifying x, y coordinates for Component:
  • This becomes tedious for even mildly complex GUIs.
  • Addition of more components requires recalculation of every component’s x, y coordinate
  • If container resizes (e.g., user expands window), calculations have to be redone!
  • Solution:
  • Position components based on a percentage of available container size. Or create an algorithm to place components . . .
  • But Java already does this for you . . .
slide49

Layout Managers -- AWT Based

  • Java provides several layout managers.
  • We will concentrate here on several of them:
    • BorderLayout
    • GridLayout
    • FlowLayout
    • BoxLayout
  • To tell a container which layout manager to use, invoke the method:
  • setLayout( );
  • and specify a type of layout.
  • For example:
  • To specify a BorderLayout:
  • setLayout (new BorderLayout());
layout managers two general flavors
Layout Managers: Two General Flavors
  • One can conceptually divide layout managers into two types:
    • Those that attach constraints to their components.
    • Those that do not.
  • What does this mean, "attach constraints"?If a manager attaches constraints to a component, then information about a component’s location (e.g., compass points) is stored with the object.
slide51

NORTH

WEST

CENTER

EAST

SOUTH

Border Layout

BorderLayout specifies the arrangement:

  • To add components to a BorderLayout, specify the position in which the component will reside.
  • Only one component (or container) can go in each of the five positions.
slide52

Border Layout--Example

  • setLayout (new BorderLayout());
  • add(new Label ("Hello!"), "North");
  • Canvas myCanvas = new Canvas();
  • // more about Canvas in a moment
  • add (myCanvas, "Center");

Hello!

{ a fresh canvas

for drawing here}

layout manager no constraints
Layout Manager: No Constraints
  • The second type of LayoutManager does not specify constraints for the objects it holds.
  • Examples:
    • GridLayout()
    • FlowLayout()
  • Without constraints, you cannot accurately predict layout behavior across platforms
layout manager no constraints54
Layout Manager: No Constraints

import java.awt.*;

public class FlowTest extends Frame {

String Labels[] = {"Short", "Short", "Long Label",

"Really Long Label", "Really, really long"};

public FlowTest(){

this.setSize(400,200);

setLayout(new FlowLayout());

for (int i = 0; i < Labels.length; i++){

Button temp = new Button (Labels[i]);

add (temp);

}

}

public static void main (String arg[]){

new FlowTest().show();

}

} //class test

layout manager no constraints58
Layout Manager: No Constraints
  • Note:
    • Since pixels, fonts and insets vary with each platform, layout without constraints will vary greatly.
  • Lesson:
    • Use layout managers without constraints only when you have few components, or you’ve anticipated their possible movement.
basic graphics61
Basic Graphics

Graphics Principles

  • Containers
  • Components
  • Layouts
  • Events

Learning Objectives

Basics of Java Graphics

objective62
Objective

(demo GraphicApp)

events
Events
  • Behind the scenes, the Java runtime environment is monitoring many things
  • When any of a number of things happen an event is said to occur. Sometimes the terminology is “an event gets fired"
  • Examples of the types of things that can "fire" events
    • Pressing a key on the keyboard
    • Clicking on a component (like a button)
    • Entering a component with the mouse pointer
    • Have a timer "time-out"
events64
Events
  • Moving the mouse around any reasonably complicated GUI can literally cause hundreds if not thousands of events to occur
  • Events will be ignored except for the ones that you tell Java that you are interested in doing something about
  • Java maintains a data structure of all the events that you have decided to handle and looks up events and does what you tell it to do.
remember this
Remember this???

import java.awt.*;

public class HelloGUI {

public static void main (String[ ] arg) {

System.out.println("About to make GUI");

Frame f = new Frame ("Hello GUI");

f.setSize( 200, 200 );

f.show();

System.out.println("Finished making GUI");

}// main

} // class HelloGUI

diagramatically
Diagramatically

User Code

Java Guts

Event Q

Event

class HelloGUIE

main {

Frame f

Handler h

… <register h>

f.show()

}

while (true) {

if (!q.empty()) {

dequeue an event

if(someone wants it)

call the right method

}

}

class eventHandler

public void thisEvent(){

}

so we could write a class like this
So we could write a class like this

import java.awt.*;

import java.awt.event.*;

public class Handler implements WindowListener

{

public void windowActivated(WindowEvent e) {}

public void windowClosed(WindowEvent e) {}

public void windowClosing(WindowEvent e)

{

Window w = e.getWindow();

w.setVisible(false);

w.dispose();

System.exit(0);

}

public void windowDeactivated(WindowEvent e) {}

public void windowDeiconified(WindowEvent e) {}

public void windowIconified(WindowEvent e) {}

public void windowOpened(WindowEvent e) {}

}

making it work
Making it work
  • Write the handler exactly to the specification of a WindowListener found in the API.
    • This is not inheritance; you must write all of the methods in the specification.
    • You only need to provide bodies for the events you want to receive
    • The implements key word merely enforces the specification
  • Register the handler with Java.
    • That is, tell Java in which class the method will be located to run when the Window Closing Event occurs.
registration
Registration

import java.awt.*;

public class HelloGUIE

{

public static void main (String[ ] arg) {

// local variable h

Handler h = new Handler();

System.out.println ("About to make GUI");

// local variable f

Frame f = new Frame ("Hello GUI");

f.setSize( 200, 200 );

f.addWindowListener(h);

f.show();

System.out.println("Finished making GUI");

} // main

} // class HelloGUIE

smiley graphics project
Smiley Graphics Project
  • We have designed the first Graphics project to make custom cartoon development as easy as possible
  • Consists of 3 classes:
    • GraphicsApp –a frame containing a Canvas in the center, a panel of buttons in the South, and the event handlers for the buttons.
      • Buttons include Start, Stop and as many other buttons as are specified in the Cartoon class
      • The event handlers call methods in the Cartoon class
    • MyPanel – provides the timer functionality and paints on the canvas
    • Cartoon – a collection of data and callback functions to mechanize a specific cartoon
the custom class
The Custom class
  • Written to cover up the nasty details of more complex Java handlers
  • Provides functionality for your specific cartoon
  • Functionality implemented as “callback functions”

Cartoon

X

Y

Smile

Wink

doButton

timerTick

doPaint

cartoon class outline
Cartoon Class Outline

public class Cartoon {

// <data>

public Cartoon (Dimension d) {

// <initialization>

}

public void doButton(int code) {

// <button code>

}

public void timerTick() {

// <timer code>

}

public void doPaint(Graphics g) {

// <painting code>

}

}

global data

Constructor to initialize the global data

Process the press of each button

Process the tick of a clock

Process the paint command

cartoon class for smiley data
Cartoon Class for Smiley - data

public class Cartoon{

public static String Labels[] = { "Smile", "Frown", "Wink" };

Dimension screenSize;

private boolean smile;

private boolean wink;

private boolean winking;

private int x;

private int y;

private int dx;

private int count;

public final int DX = 2;

public final int MARGIN = 50;

public Cartoon(Dimension d) {

smile = true;

wink = false;

winking = false;

x = d.width/2;

y = d.height/2;

dx = DX;

screenSize = d;

}

// <continued>

Labels for the cartoon buttons (Start and Stop are built in)

Global control data

Initialize global data

cartoon class for smiley buttons
Cartoon Class for Smiley - buttons

<continued>

/**

* respond to custom button press

* @param code the number of the button pressed

* (0 ... (Labels.length-1) )

*/

public void doButton(int code) {

switch(code) {

case 0: // Smile

smile = true;

break;

case 1: // Frown

smile = false;

break;

case 2: // Wink

winking = !winking;

if(!winking) wink = false;

break;

}

}

// <continued>

cartoon class for smiley timer
Cartoon Class for Smiley - timer

// <continued>

/**

* hit here each clock tick

*/

public void timerTick() {

count++;

if( winking && (count%30 == 0)) wink = !wink;

x = x + dx;

if( x > (screenSize.width - MARGIN) ) {

dx = -DX;

smile = !smile;

}

if( x < MARGIN ) dx = DX;

}

// <continued>

cartoon class for smiley painting
Cartoon Class for Smiley - painting

// <continued>

public void doPaint(Graphics g) {

g.setColor(Color.yellow);

g.fillOval(x, y-50, 300, 300);

g.setColor(Color.black);

g.drawOval(x, y-50, 300, 300); // frame

if( smile ) {

g.drawArc(x+50, y, 200, 200, 225, 90); // smile

g.drawArc(x+50, y, 200, 199, 225, 90);

g.drawArc(x+50, y, 200, 198, 225, 90);

} else {

g.drawArc(x+50, y+175, 200, 200, 45, 90); // frown

g.drawArc(x+50, y+174, 200, 199, 45, 90);

g.drawArc(x+50, y+173, 200, 198, 45, 90);

}

if( wink ) { // right eye

g.drawArc(x+75, y+50, 50, 50, 180, 180 );

g.drawArc(x+75, y+50, 50, 49, 180, 180 );

g.drawArc(x+75, y+50, 50, 48, 180, 180 );

} else {

g.fillOval(x+75, y+50, 50, 50);

}

g.fillOval(x+175, y+50, 50, 50); // left eye

g.fillRect(x+140, y+100, 20, 50); // nose

}

}

Check the Java API under Graphics for all the drawing commands

diagramatically79
Diagramatically

User Code

Java Guts

Event Q

Event

class HelloGUIE

main {

Frame f

Handler h

… <register h>

f.show()

}

while (true) {

if (!q.empty()) {

dequeue an event

if(someone wants it)

call the right method

}

}

class eventHandler

public void thisEvent(){

Cartoon.doAction();

}

key ideas
Key Ideas
  • Thousands of events are generated by Windows
  • We choose which events we want to process and Java ignores the rest
  • To simplify life, we have built a Cartoon class that is connected to the appropriate events
  • The Cartoon class has methods to process buttons, timer ticks and paint commands