Io package as Java’s basic I/O system continue’d.

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

Event Handling.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
CS 178: Programming with Multimedia Objects Aditya P. Mathur Professor of Computer Sciences Purdue University, West Lafayette Sept 9, 2004 Last update:
Event Handling Events and Listeners Timers and Animation.
Lecture 24 Applets. Introduction to Applets Applets should NOT have main method but rather init, stop, paint etc They should be run through javac compiler.
Programming Applets How do Applets work ? This is an HTML page This is the applet’s code It has a link to an applet.
Java Programming, 3e Concepts and Techniques Chapter 3 Manipulating Data Using Methods.
1 Gui Programming (Part I) Graphical User Interfaces (Part I) l Introduction to events. l A Brief history. l Event sources and listeners. l The delegation.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
Java Programming, 2E Introductory Concepts and Techniques Chapter 3 Manipulating Data Using Methods.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Lecture 2 Exception handling Advanced Java Programming 1 dr inż. Wojciech Bieniecki
Dale Roberts GUI Programming using Java - Event Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
Event Handling Mohanraj S AP / IT Angel College of Engg & Tech.,
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Overloading There is another aspect to polymorphism: Overloading Overloading is not overriding. In Turkish: Overridding: eskisini (geçersiz kılmak) Overloading:
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Object Oriented Programming.  Interface  Event Handling.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Index Event Handling Events Event Source Event Listener Event Classes Action Event Class Adjustment event Class Event Source Event Listener Interface Using.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
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.
Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Java Input and Output. Java Input  Input is any information needed by your program to complete its execution  So far we have been using InputBox for.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
I/O in java and Revision. 2 I/O in Java Many packages and libraries associated with Java provide sophisticated ways to input and output information, e.g.:
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.
Event Driven (Asynchronous) Programming. Event handling in Unity Subclass a class that contains event handling methods, and then override those methods.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
GUI Programming using Java - Event Handling
CSC 205 Programming II Lecture 5 AWT - I.
CompSci 230 S Programming Techniques
A First Look at GUI Applications
Lecture 09 Applets.
I/O Basics.
Programming in Java Event Handling
Ellen Walker Hiram College
GUI Programming III: Events
I/O Streams- Basics Byte Streams and Character Streams
Programming in Java Files and I/O Streams
Introduction to Event Handling
L3. Necessary Java Programming Techniques
L3. Necessary Java Programming Techniques
Constructors, GUI’s(Using Swing) and ActionListner
I/O and Applet from Chapter 12
Presentation transcript:

io package as Java’s basic I/O system continue’d

import java.io.*; public class Read { public static void main ( String args[]) throws IOException { BufferedReader br= new BufferedReader (new InputStreamReader(System.in)); String str; System.out.println("Enter your name"); str = br.readLine(); System.out.println("Your name is " + str); }

//An editor example. import java.io.*; class Editor { public static void main (String args[]) throws IOException { //create a BufferedReader using System. in BufferedReader br= new BufferedReader (new InputStreamReader(System.in)); String str[] = new String [100]; System.out.println (“Enter lines of text.”); System.out.println (“Enter ‘Stop’ to quit.”); for (int i= 0 ; i<100 ;i++) { str[i] = br.readLine(); if (str[i].equals (“stop”)) break; } System.out.println(“\nHere is your file:”); //display the lines for (int=0; i<0 ;i++) { if (str[i].equals (“stop”)) break; System.out.println(str[i]); } } }

HERE IS A SAMPLE RUN C:\JBUILDER8\JDK1.4\bin\javaw- classpath"C:\WINDOWS\jbproject\untitled40\classes;C:\ JBUILDER 8\JDK1.4\JRE\classes;C:\JBUILDER8\jdk1.4\lib\tools.jar" untitled40.Editor Enter lines of text. Enter ‘Stop’ to quit stop Here is your file:

Writing Console Output  Console output is most easily achieved with print() and println()  These methods are defined by the class PrintStream  which is the type of the object referenced by System.out  Even though System. out is a byte stream, using it for simple program output is acceptable. Shortly;  PrintSteam is an output stream derived from OutputStream,  And it implements the low-level method write()  write() can be used to write to the console.  The simples form of write() defined by PrintStream is: void write (int byteval) throws IOException  write method writes to the file the byte specified by byteval.  byteval is declared as an integer, only the low order eight bits are written.

Demonstrating the System.out.write() method package untitled41; import java.io.*; //This is a short example that uses write() to output character “1” followed by a new line to the screen class WriteDemo { public static void main (String args[]) { int a; a='1'; System.out.write(a); System.out.write('\n'); }

The PrintWriter Class  Using System.out to write to the console is possible under Java. But:  Its use is recommended mostly for debugging purposes or for sample programs such as we studied in this course  For real world programs, the recommended method of writing to the console is through a PrintWriter stream.  PrintWriter is one of the character-based classes.  Using this class for console output makes easier to internationalize the program PrintWriter defines several constructors. The one is: PrintWriter(OutputStream outputStream, boolean flushOnNewline)

PrintWriter(OutputStream outputStream, boolean flushOnNewline)  outputStream is an object type OutputStream  flushOnNewLine controls whether Java flushes the output stream every time a newline (‘\’) character is output.  If flushOnNewline is true, flushing automatically takes place.  If false, flushing is not automatic  PrintWriter supports the print() and println() methods for all types including Object. Finally:

 We can use these methods in the same way as they have been used with System.out.  If an argument is not a simple type, the PrintWriter methods call the object’s toString() method and then print the result  To write to the console by using a PrintWriter, specify System.out for the output stream and flush the stream after each newline. For example:  The fallowing line of code creates a PrintWriter that is connected to console output: PrintWriter pw= new PrintWriter(System.out, true);

//Demonstration of the running of PrintWriter method import java.io.*; public class PrintWriterDemo { Public static void main (String args [] ) { PrintWriter pw= new PrintWriter(System.out, true); pw.println (“This is a string”); int i=-7; pw.println(i); double d=4.5e-7; pw.println(d); } } Since no there is no advantage to use PrintWriter in the simple programs., We can use System.out to write simple text output to the console. The output is: untitled42.PrintWriterDemo This is a string E-7

Using URLs in Applets Network Access  To access a remote URL we need to establish a network connection.  Java offers several ways of doing this URL connections Sockets In any case we need to use the java.net package in addition to applet, GUI-elements and event handling. import java.applet.* import java.awt.*; import java.awt.event.*; import java.net.*;

Event Handling  Events are supported by java.awt.event package  Event model defines standard and consistent mechanism to generate and process events  A source generates an event and sends it to one or more listeners.  In this scheme, the listener simply waits until it receives an event  Once received, the listener processes the event and then returns  Every time the user types a character or pushes a mouse button, an event occurs.  Any object can be notified of the event.  All it has to do is implement the appropriate interface and be registered as an event listener on the appropriate event source.

 Events can be generated as a consequence of a person interacting with elements in a graphical user interface.  In addition to pressing a button, other activities to be generated are:  entering a character via the keyboard,  selecting an item in a list,  clicking the mouse.  Events may also occur that are not directly caused by interactions with a user interface  For example, an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, an operation is completed.

Event Listeners  A listener is an object that is notified when an event occurs  It has two major requirements:  It must have been registered with one or more sources to receive notifications about specific types of events  It must implement methods to receive and process these notifications.

Event Classes  The classes that represent events are core of Java’s event handling mechanism.  The root of java event class hierarchy is EventObject, which is in java.util.  EventObject is the superclass for all events.  Its one constructor is: EventObject (Object src) src is the object that generates this event.  EventObject contains two methods: getSource(): returns the source of the event toString(): returns the string equivalent of the event. The class AWTEvent defined within the java.awt package is: a superclass of all AWT events that are handled by the delegation event model. a subclass of EventObject

How to Implement an Event Handler Every event handler requires three bits of code:  In the declaration for the event handler class, code that specifies that the class either implements a listener interface or extends a class that implements a listener interface. public class MyClass implements ActionListener {  Code that registers an instance of the event handler class as a listener upon one or more components aComponent.addActionListener(instanceOfMyclass)  Code that implements the methods in the listener interface. For example: public void actionPerformed(ActionEvent e) {...//code that reacts to the action... }

Handling Action Events  Action events are fired by subclasses of AbstractButton and includes buttons, checkboxes, and menus. AbstractButton button = new JButton ("OK"); button.addActionListener(new MyActionListener()); public class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent evt) { // Determine which abstract button fired the event. AbstractButton button = (AbstractButton)evt.getSource(); }

import java.applet.*; import java.awt.*; import java.awt.event.*; import java.net.*; public class URLApplet extends Applet implements ActionListener { private TextField URLText = null ; private Button URLButton = null; public URLApplet() { } public void init() { add(new Label ("URL")); URLText = new TextField (30); add (URLText); URLButton = new Button ("Go"); add (URLButton); URLButton.addActionListener(this); }

public void actionPerformed (ActionEvent e) { String actionCommand = e.getActionCommand(); if (e.getSource() instanceof Button) if (actionCommand.equals ("Go")) { System.out.println ("Go"); try { AppletContext context = getAppletContext(); URL url = new URL(URLText.getText()); context.showDocument(url); } catch(Exception ex) { showStatus ("Error "+ex); }