OOP Assignment V. For example, the scrolling text (moving banner) problem without a thread looks like:

Similar documents
Lecture 5: Java Graphics

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

G51PRG: Introduction to Programming Second semester Applets and graphics

CS108, Stanford Handout #22. Thread 3 GUI

Graphical User Interfaces 2

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

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

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.

Programmierpraktikum

FirstSwingFrame.java Page 1 of 1

H212 Introduction to Software Systems Honors

Lecture 3: Java Graphics & Events

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

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!

Graphic User Interfaces. - GUI concepts - Swing - AWT

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

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

Come & Join Us at VUSTUDENTS.net

Applet which displays a simulated trackball in the upper half of its window.

Java: Graphical User Interfaces (GUI)

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

PESIT Bangalore South Campus

Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.

User interfaces and Swing

Introduction to the JAVA UI classes Advanced HCI IAT351

CS 251 Intermediate Programming GUIs: Event Listeners

Question 1. Show the steps that are involved in sorting the string SORTME using the quicksort algorithm given below.

Advanced Java Unit 6: Review of Graphics and Events

AP CS Unit 11: Graphics and Events

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a

First Name: AITI 2004: Exam 2 July 19, 2004

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

First Name: AITI 2004: Exam 2 July 19, 2004

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

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

Midterm assessment - MAKEUP Fall 2010

Day before tests of Java Final test. IDM institution of Bandarawela. Project for department of education

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

TYPES OF INTERACTORS Prasun Dewan Department of Computer Science University of North Carolina at Chapel Hill

COMPSCI 230. Software Design and Construction. Swing

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

Java. GUI building with the AWT

Graphical User Interfaces 2

Graphical User Interfaces (GUIs)

II 12, JFileChooser. , 2. SolidEllipse ( 2), PolyLine.java ( 3). Draw.java

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

1 Looping Constructs (4 minutes, 2 points)

CSIS 10A Assignment 14 SOLUTIONS

CSC 1214: Object-Oriented Programming

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

Graphical User Interfaces 2

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Packages: Putting Classes Together

Check out ThreadsIntro project from SVN. Threads and Animation

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

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

Programming Languages and Techniques (CIS120)

Which of the following syntax used to attach an input stream to console?

HW#1: Pencil Me In Status!? How was Homework #1? Reminder: Handouts. Homework #2: Java Draw Demo. 3 Handout for today! Lecture-Homework mapping.

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

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

IT101. Graphical User Interface

Computer Science 210: Data Structures. Intro to Java Graphics

Advanced Java Programming

SD Module-1 Advanced JAVA

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

Class 34: Introduction to Threads

Java for Interfaces and Networks (DT3010, HT10)

SD Module-1 Advanced JAVA. Assignment No. 4

ASSIGNMENT NO 14. Objectives: To learn and demonstrated use of applet and swing components

Module 5 Applets About Applets Hierarchy of Applet Life Cycle of an Applet

Programmierpraktikum

Java Programming Lecture 6

Graphical User Interface (GUI)

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...

Chapter 1 GUI Applications

Graphical User Interface (GUI)

AP CS Unit 12: Drawing and Mouse Events

MIT AITI Swing Event Model Lecture 17

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

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

Systems Programming Graphical User Interfaces

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

Unit 7: Event driven programming

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

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

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

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

Darshan Institute of Engineering & Technology for Diploma Studies

AP Computer Science Unit 13. Still More Graphics and Animation.

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Contents. iii Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services August 1998, Revision B

Lecture 19 GUI Events

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

Stream Manipulation. Lecture 11

2. (True/False) All methods in an interface must be declared public.

Swing Programming Example Number 2

Transcription:

OOP Assignment V If we don t use multithreading, or a timer, and update the contents of the applet continuously by calling the repaint() method, the processor has to update frames at a blinding rate. Too many calls to the paint() method might be coalesced (effectively ignored) and will block the GUI, making the applet unresponsive. For example, the scrolling text (moving banner) problem without a thread looks like: // Imports and shit public class TextScrollNoT extends Applet { String text; public void init () { public void start() { text = // get text while (true) { char ch = text.charat(0); text = text.substring(1, text.length()) + ch; public void paint(graphics g) { g.drawstring(text, 20, 90); Here the repaint() method is being called many times per second (depending on the processor speed) on the main thread, too many calls being the reason for the GUI block and unresponsiveness, and undesired output. The same problem with threads looks like: // Imports and shit public class TextScroll extends Applet implements Runnable { String text; public void init () { public void start() { text = // Get text Thread t = new Thread(this); t.start();

public void run() { char ch; try { while (true) { Thread.sleep(150); ch = text.charat(0); text = text.substring(1, text.length()) + ch; catch (InterruptedException e) { public void paint(graphics g) { g.drawstring(text, 20, 90); The use of a thread shifts the overhead of updating the frames to a child thread instead of bulking up the main thread, making the UI responsive. The use of the sleep() method causes the updating calls to wait a while before performing the next update, reducing the number of times the GUI is refreshed, giving the desired output. The java window manager sends a program an Event notification when a certain action such as mouse movement, key presses, selections, etc. are preformed. The window manager generates various kinds of events the program needn't listen to. A program must specify what kind of events it wants to receive. This is done by installing appropriate Event Listener objects. The UI component that generates the event is called the Event Source (duh). An Event Listener performs a check on when a Event has occurred, and takes appropriate action accordingly. For example, we want to draw a line based on the mouse movement. To achieve this, we will 1. Listen to the MouseEvent 2. Add appropriate MouseListener and MouseMotionListeners 3. Perform the action (draw line in this case) based on the listeners.

import java.awt.*; import java.applet.*; import java.awt.event.*; /* <applet code="drawline" width=848 height=480> * </applet> * */ public class DrawLine extends Applet { Point startpoint, endpoint; public DrawLine () { // For pressing and releasing addmouselistener(new MouseAdapter() { public void mousepressed (MouseEvent e) { super.mousepressed(e); startpoint = e.getpoint(); ); public void mousereleased (MouseEvent e) { super.mousereleased(e); endpoint = e.getpoint(); // For the motion event addmousemotionlistener(new MouseMotionAdapter() { public void mousedragged (MouseEvent e) { endpoint = e.getpoint(); ); public void init () { super.init(); public void paint (Graphics g) { super.paint(g); g.drawline(startpoint.x, endpoint.x, startpoint.y, endpoint.y);

// PrimitveReadWrite.java import java.io.*; public class PrimitveReadWrite { public static void main (String [] args) throws IOException { FileOutputStream fout = new FileOutputStream("Test.dat"); DataOutputStream dos = new DataOutputStream(fout); dos.writedouble(1812.4008); dos.writeint(666); dos.writechar('x'); dos.close(); BufferedInputStream bufferedinput = new BufferedInputStream(new FileInputStream("Test.dat")); byte[] buffer = new byte[22]; bufferedinput.read(buffer); System.out.print("\n\nRaw Read: "); System.out.write(buffer); // Raw Read: @?Q?kP???X FileInputStream fin = new FileInputStream("Test.dat"); DataInputStream din = new DataInputStream(fin); double d = din.readdouble(); int i = din.readint(); char c = din.readchar(); System.out.println("\n\nPrimitve read: " + d + ", " + i + ", " + c); din.close(); // Primitve read: 1812.4008, 666, X // Content in the file (visible): @?Q?kP???X

import java.io.*; public class Copy3 { public static void main (String [] args) throws IOException, FileNotFoundException { File source = null; File dest = null; InputStream is = null; OutputStream os = null; try { source = new File(args[0]); dest = new File(args[1]); is = new FileInputStream(source); os = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); finally { is.close(); os.close();

A class that has no name, and is defined inside another class is called an anonymous inner class. It is used to override a method of a class or an interface. The java compiler automatically creates a class whenever required. For example in swing based programs: import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SumApplication { JTextField field1, field2; JButton computebutton; JLabel labelsum; public SumApplication () { JFrame frame = new JFrame("Number Operations"); frame.setsize(600, 400); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setlayout(new FlowLayout()); field1 = new JTextField(""); field2 = new JTextField(""); JPanel fieldpanel = new JPanel(new GridLayout(3, 1)); computebutton = new JButton("Compute"); computebutton.addactionlistener(new ActionListener() { // Inner class is made here public void actionperformed(actionevent e) { double a = 0.0, b = 0.0; double sum = 0.0; try { a = Double.parseDouble(field1.getText()); b = Double.parseDouble(field2.getText()); sum = a + b; sum); ); catch (Exception e1) { // Handle error and shit finally { labelsum.settext(" " + a + "\n+ " + b + "\n= " +

fieldpanel.add(field1); fieldpanel.add(field2); fieldpanel.add(computebutton); labelsum = new JLabel("", JLabel.CENTER); frame.add(fieldpanel); frame.add(labelsum); frame.setvisible(true); public static void main (String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new SumApplication(); ); The above program on compilation generates three.class files, one for the main class and two for each of the anonymous inner classes created: 1. ActionListener class object added to the computebutton as an action listener 2. Inner class implementing the Runnable interface, inferred from the SwingUtilities.invokeLater block, that dispatches the applet to a child thread.