Applications of Java to Physics Teaching (Part II) S S Tong Department of Physics CUHK.

Slides:



Advertisements
Similar presentations
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Advertisements

Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
Using Thread for Animation. Threads When we are doing multiple things at once we say we are multitasking Computers multitask when they run several programs.
Computer Science 209 Graphics and GUIs. Working with Color The class java.awt.Color includes constants for typical color values and also supports the.
Object Oriented Programming Lecture 7: Algorithm animation using strategy and factory patterns, The Adapter design pattern
Jan Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg.
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Event Handling Events and Listeners Timers and Animation.
CS3157 Java UI Recitation. Material Covered: Overview of AWT components, Event Handling, creating applets, and sample UI. Not covered in recitation: Drawing,
GUI Event Handling Nithya Raman. What is an Event? GUI components communicate with the rest of the applications through events. The source of an event.
Event Handling in Java CSE Software Engineering Spring 2000 By Prasad.
Java: Animation Chris North cs3724: HCI. Animation? Changing graphics over time Examples: cartoons Clippy, agents/assistants Hour glass Save dohicky Progress.
Lesson 35: Review of the Java GUI. The JFrame, Container and JButton.
Io package as Java’s basic I/O system continue’d.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
Cs884(Prasad)java12AWT1 Abstract Windowing Toolkit Support for Graphical User Interface (Event-driven programming)
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
Applets Session 8. Java Simplified / Session 8 / 2 of 31 Review The Abstract Windowing Toolkit (AWT) is a set of classes that allow us to create a graphical.
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
CS 112 Department of Computer Science George Mason University CS 112 Department of Computer Science George Mason University Writing Graphic Applications.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
7/3/00SEM107- © Kamin & ReddyClass 11 - Events - 1 Class 11 - Events r A couple of odds & ends m Component sizes  switch statement r Event types r Catching.
Previous programs used a JLabel for OUTPUT. Another Swing component that can be used for both user input and output is the JTextfield. Suppose we want.
Lesson 34: Layering Images with Java GUI. The FlowLayout RECAP.
Field Trip #19 Animations with Java By Keith Lynn.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
The Drawing program – Java Applets
Copyright © 2002, Systems and Computer Engineering, Carleton University b-Gui2.ppt * Object-Oriented Software Development Part 18-b Building.
Swing Differences between Swing and AWT Naming Conventions All Swing components begin with a capital J -- JPanel, JButton, JScrollBar, JApplet, etc..
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Chapter 7: Pinball Game Construction Kit. Vectors Example of a “collection class” Must “import java.util.Vector” More flexible than arrays: will grow.
Concurrent Programming and Threads Threads Blocking a User Interface.
For (int i = 1; i
UID – Event Handling and Listeners Boriana Koleva
Event Handling. 2 GUIs are event driven –Generate events when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc.
Introduction to Java Programming
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
Kim B. Bruce, Andrea Danyluk & Tom Murtagh Williams College † Partially supported by NSF CCLI grant DUE Java: An Eventful Approach An innovative.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
CS Lecture 04 Mice Lynda Thomas
Graphical User Interfaces (GUI). PART ONE About GUI’s.
1 Event Handling – Lecture 4 Prepared by: Ahmad Ramin Rahimee Assistant Professor ICTI.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 10.
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
Event Listeners ActionListener –button,list AdjustmentListener-scroll bar ComponentListener-when component hidden…. ContainerListener-comp added or removed.
CSI 3125, Preliminaries, page 1 Event Handling. CSI 3125, Preliminaries, page 2 Event Handling An Event Change in the state of an object is known as event.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
1 IM103 week 8 (C&K ch17, p412) Advanced graphic programming Learning objectives By the end of this chapter you should be able to:  create dialogue windows.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Event Handling CS 21a: Introduction to Computing I First Semester,
Java Applets Adding Animation. Import Files You still need to include the same files: –import java.applet.*; –import java.awt.*;
TENTH LECTURE Event and listener. Events and Listeners An event can be defined as a type of signal to the program that something has happened. The event.
Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
CSC 205 Programming II Lecture 5 AWT - I.
Events and Event Handling
Chapter 14 Event-Driven Programming
CompSci 230 S Programming Techniques
Chapter 12 Event-Driven Programming
INFSY 547: WEB-Based Technologies
Computer Science 209 Graphics and GUIs.
Programming in Java Event Handling
GUI Event Handling Nithya Raman.
GUI Programming III: Events
CSE Software Engineering Fall 1999 Updated by J. Brown
Event-driven programming for GUI
Programming Graphical User Interface (GUI)
Presentation transcript:

Applications of Java to Physics Teaching (Part II) S S Tong Department of Physics CUHK

6. Simple Animations 4 Animations –many frames displayed in a given order 4 Thread –part of the program running on its own –multi-tasking (actually multi-threading) 4 How to –create a thread? –display the frames? –terminate the thread under certain conditions?

 Implement the interface Runnable  Declare a Thread public class Spin extends Applet implements Runnable { Thread runner = null; }  Create and run a Thread runner = new Thread(this); runner.start(); 4 Load a series of image for (int i = 0; i < 16; i++) spin[i] = getImage(getCodeBase(), "images/Spin" + i + ".gif"); calls the run() method

 Create a loop, call the paint method repeatedly public void run() { int i = 0; while (runner != null) { currentImage = spin[i]; repaint(); i++; if (i > 15) i = 0; pause(50); } public void paint(Graphics screen) { if (currentImage != null) { screen.drawImage( currentImage, 100, 100, this); }

4 Flow of the applet run() loop inside while (...) { } paint(...) draw images runner.start() repaint() init() images loaded...getImage(...) Thread created and initialized...new Thread(this) call paint(...) once 4 Stop a thread runner.stop(); runner = null;

4 Reduce flickering –Override the update(...) method, so that the screen is not erased before repainting –Create an off-screen image and a Graphics object do all drawing on the off-screen image first replace the on-screen image with the updated off-screen image Graphics offScreen; Image offScreenImage; public void init() { offScreenImage = createImage(300,300); public void update(Graphics screen) { paint(screen); } call the paint method directly

4 Reduce flickering (contiune) public void paint(Graphics screen) { j++; offScreen = offScreenImage.getGraphics(); if (currentImage != null) { offScreen.setColor(Color.white); offScreen.fillRect(0,0,300,300); offScreen.drawImage(currentImage, 100, 100, this); offScreen.setColor(Color.red); offScreen.drawString("Frame no " + j, 30, 30); screen.drawImage(offScreenImage, 0, 0, this); } associate the off-screen image and Graphicserasing off-screen drawing off-screen put the off-screen image on-screen

7 Building simple interface 4 Basic components Label Button Checkbox Choice TextField

4 Adding components to an applet –Declare the object type theButton = new Button("I am a button"); theCheckbox = new Checkbox("I am a checkbox"); theChoice = new Choice(); theChoice.add("I am item 1"); theChoice.add("I am item 2"); theChoice.add("I am item 3"); theField = new TextField("long field", 20); Button theButton; Checkbox theCheckbox; Choice theChoice; TextField theField; –Assign labels and attributes to the components items lengthcontents –Add the components to the applet add(...);

4 Canvas - an area for drawing –create a subclass of Canvas class MyCanvas extends Canvas { MyCanvas() { setBackground(Color.cyan); setSize(300,300); } public void paint(Graphics screen) { } –create an instance of this subclass in the applet canvas = new MyCanvas(); draw something on the canvas set background colorset size –repaint the canvas canvas.repaint();

4 How to arrange the components? –Use Layout Manager  We discuss the BorderLayout() only public void init() { setLayout(new BorderLayout()); North South CenterEastWest

–Adding components add("South", buttonA); add("Center", canvasB); –Using a panel Panel p = new Panel(); p.add(theLabel); p.add(theButton); add("South",p) add("Center", canvas);

4 Firing events from the components –Listeners: ActionListener for Button ItemListener for Choice and Checkbox –Implementing the Listeners import java.awt.event.*; public class EventTest extends Applet implements ActionListener, ItemListener { Listeners are interfaces –Adding Listeners to the component button1.addActionListener(this); theChoice.addItemListener(this); theCheckbox.addItemListener(this);

public void itemStateChanged(ItemEvent evt) { if (evt.getSource() == theChoice) { int itemNo = theChoice.getSelectedIndex(); if (evt.getSource() == theCheckbox) { boolean boxState = theCheckbox.getState(); –Buttons trigger the actionPerformed method public void actionPerformed(ActionEvent evt) { if (evt.getSource() == button1) if (evt.getSource() == button2) canvas.repaint(); } identify which component triggers the event –Choice menus and checkboxes trigger itemStateChanged method get the index of the selected item get the state (true/false) of the checkbox

–Updating the canvas import java.awt.event.*; public class EventTest extends Applet implements ActionListener, ItemListener { String currentString = ""; public void actionPerformed(ActionEvent evt) { canvas.repaint(); } public void itemStateChanged(ItemEvent evt) { canvas.repaint(); } class EventCanvas extends Canvas { screen.drawString(currentString, 50, 50); } EventCanvas is defined inside EventTest - an inner class

class MyTextField extends TextField { MyTextField(String s, int l) { super(s,l); } double getNumber() { return Double.valueOf( getText()).doubleValue(); } void setNumber(double num) { setText(String.valueOf(num)); } 4 Number I/O for a TextField field.getText() gives the text of field field.setText("string") sets the text of field to "string" –Converting numbers to strings and vice versa call to the superclass's constructor string  double double  string

 Example AnimateWaves.java –superposition of two waves –amplitude, wavelengths, periods read from text fields –mode of display - choice menu –start and stop - buttons  Exercise ProjectileEx.java –initial position and velocity read from text fields –start and reset - buttons  Example ShootHead.java –Modification of Projectile.java –Shooting a free-falling object

4 Listening to mouse events –Listeners: MouseListener mouse pressed, released, enter, exit MouseMotionListener mouse moved, dragged –Implementing the Listeners import java.awt.event.*; public class EventTest extends Applet implements MouseListener, MouseMotionListener { –Adding Listeners to the component canvas.addMouseListener(this); canvas.addMouseMotionListener(this); Listeners are interfaces

–Let the canvas listens to mouse events –Interact with hot spots, drag and drop objects etc. public void mouseMoved(MouseEvent evt) {...} public void mouseDragged(MouseEvent evt) {...} public void mousePressed(MouseEvent evt) {...} public void mouseClicked(MouseEvent evt) {...} public void mouseReleased(MouseEvent evt) {...} public void mouseEntered(MouseEvent evt) {...} public void mouseExited(MouseEvent evt) {...} –Mouse motion events trigger –Mouse events trigger –Gets the mouse position inside this methods e.g., Point p = evt.getPoint();

 Example AddVectors.java –addition and subtraction of two vectors –changing the text fields updates the screen –dragging the vectors updates the text fields

8 References 4 L. Lemay and R. Cadenhead, Teach Yourself Java 2 in 21 days, SAMS 4 M. Campione and K. Walrath, The Java Tutorial (2nd Ed), Addison Wesley 4