Review Session for EXCEPTIONS & GUI -Ankur Agarwal 1.

Slides:



Advertisements
Similar presentations
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Advertisements

Event Handling Events and Listeners Timers and Animation.
Unit 12 Object-oriented programming: Event-driven programming for GUI Jin Sa.
Graphical User Interfaces Allow for interaction with –Buttons –Menus –Text Fields Two Java Libraries to assist in GUI Programming –AWT –Swing.
CS/ENGRD 2110 FALL 2014 Lecture 15: Graphical User Interfaces (GUIs): Listening to events 1.
1 Listening to events on GUIs Sec contains this material. Corresponding lectures on ProgramLive CD is a better way to learn the material. Top finalists.
1 Class 8. 2 Chapter Objectives Use Swing components to build the GUI for a Swing program Implement an ActionListener to handle events Add interface components.
Chapter 8: Graphical User Interfaces Objectives - by the end of this chapter, you should be able to do the following: –write a simple graphical user interface.
Welcome to CIS 083 ! Events CIS 068.
Review Session for EXCEPTIONS & GUIS -David Gries 1 Adapted from Previous Review Slides.
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.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
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.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
CS2110. GUIS: Listening to Events 1 Download the demo zip file from course website and look at the demos of GUI things: sliders, scroll bars, combobox.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Copyright © 2002, Systems and Computer Engineering, Carleton University c-Gui3.ppt * Object-Oriented Software Development Part 18-c Building.
Chapter 12 1 TOPIC 13B l Buttons and Action Listeners Window Interfaces Using Swing Objects.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
CS2110. GUIS: Listening to Events Also Example of Stepwise Refinement and Anonymous classes 1 Download the demo zip file from course website and look at.
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.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
1 12 Apr 2011 GUIS: Graphical User Interfaces Their mouse had a mean time between failure of … a week … it would jam up irreparably, or... jam up on the.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
1 Lecture 25 Listening to buttons and mice Quotes by Tony Hoare There are two ways of constructing a software design: (1) make it so simple that there.
Creating a GUI Class An example of class design using inheritance and interfaces.
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
1 Listening to events on GUIs Sec contains this material. Corresponding lectures on ProgramLive CD is a better way to learn the material. Why men.
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.
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.
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.
GUI Tutorial Day 4. More GUI action  adding a Mouse Listener  SimpleDots  Simple mouse listener  Draw an oval where the mouse is clicked  Box example.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 12. Listening to events. Inner and anonymous classes Why men think “computer” should be a feminine word 1. No one but their creator understands their.
GUIs & Event-Driven Programming Chapter 11 Review.
Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
CS2110. GUIS: Listening to Events
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
CompSci 230 S Programming Techniques
Object-Orientated Analysis, Design and Programming
Final exam: Period B: Thursday, 13 May, 9:00-11:30AM, Barton East
Web Design & Development Lecture 11
A First Look at GUI Applications
CS2110. GUIS: Listening to Events
Review Session for EXCEPTIONS & GUI -Deepak Bapat
Listening to events on GUIs
Programming in Java Event Handling
Ellen Walker Hiram College
Miscellaneous Topics #6: Polygons GUI Components and Event Handlers
GUI Programming III: Events
CS2110. GUIS: Listening to Events
Event-driven programming for GUI
CS2110. GUIS: Listening to Events
CS2110. GUIS: Listening to Events
Chapter 16 Event-Driven Programming
Events, Event Handlers, and Threads
Lecture 21. Listening to events on a GUI (and development of a loop)
CS2110. GUIS: Listening to Events
12. Listening to events. Inner and anonymous classes
13 April 2010 GUIS: Graphical User Interfaces
Graphical User Interface
Presentation transcript:

Review Session for EXCEPTIONS & GUI -Ankur Agarwal 1

An Exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. Throwable Class and Its Subclasses 2 Exceptions are signals that help may be needed; they can be “handled”. Errors are signals that things are beyond help.

How do you know if a method throws an exception? The Java compiler will generate an error if a method throws an exception and you have not handled it yet. You are supposed to catch the exception to remove that error. By referring to Java Docs. Eg : charAt method from the String class public char charAt(int index) Returns the character at the specified index. An index ranges from 0 to length() - 1. The first character of the sequence is at index 0, the next at index 1, and so on, as for array indexing. Parameters: index - the index of the character.Returns: the character at the specified index of this string. The first character is at index 0. Throws: IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.IndexOutOfBoundsException 3

Writing your exception class class MyException extends Exception{ public MyException( ) { } public MyException(String msg) { super(msg); } public class Test{ public void testMethod( ){ throw new MyException( ); } Error: Unhandled exception type MyException in testMethod() 4

class MyException extends Exception{ public MyException(String msg) { super(msg); } public MyException() { } class Test{ public void testMethod( ){ try { throw new MyException( ); } catch (MyException e) { e.printStackTrace(); … } 5

Some Java Exception classes ApplicationException ArithmeticException ArrayStoreException FileNotFoundException IndexOutOfBoundsException IllegalArgumentException IllegalStateException InvalidOperationException InvalidParameterException 6

7 GUI Listening to events: mouseclick, mouse movement into or out of a window, a keystroke, etc. An event is a mouseclick, a mouse movement into or out of a window, a keystroke, etc. To be able to “listen to” a kind of event, you have to 1. Write a method that will listen to the event. 2. Let Java know that the method is defined in the class. 3. Register an instance of the class that contains the method as a listener for the event. We show you how to do this for clicks on buttons, clicks on components, and keystrokes.

8 Listening to a Button 1. Write the procedure to be called when button is clicked: /** Process click of button */ public void actionPerformed(ActionEvent ae) {... } 2. Have class implement interface ActionListener: public class C extends JFrame implements ActionListener {... } 3. Add instance of this class as an “action listener” for button: button.addActionListener(this);

9 Listening to a Button /** An instance has two buttons. Exactly one is always enabled. */ public class ButtonDemo1 extends JFrame implements ActionListener { /** Class invariant: exactly one of eastB and westB is enabled */ private JButton westB= new JButton("west"); private JButton eastB= new JButton("east"); /** Constructor: frame with title t & two buttons */ public ButtonDemo1(String t) { super(t); Container cp= getContentPane(); cp.add(westB, BorderLayout.WEST); cp.add(eastB, BorderLayout.EAST); westB.setEnabled(false); eastB.setEnabled(true); westB.addActionListener(this); eastB.addActionListener(this); pack(); setVisible(true); } /** Process a click of a button */ public void actionPerformed (ActionEvent e) { boolean b= eastB.isEnabled(); eastB.setEnabled(!b); westB.setEnabled(b); } red: listening blue: placing

10 Listening to a Button /** An instance has two buttons. Exactly one is always enabled. */ public class ButtonDemo1 extends JFrame implements ActionListener { /** Class invariant: exactly one of eastB and westB is enabled */ private JButton westB= new JButton("west"); private JButton eastB= new JButton("east"); /** Constructor: frame with title t & two buttons */ public ButtonDemo1(String t) { super(t); Container cp= getContentPane(); cp.add(westB, BorderLayout.WEST); cp.add(eastB, BorderLayout.EAST); westB.setEnabled(false); eastB.setEnabled(true); westB.addActionListener(this); eastB.addActionListener(this); pack(); setVisible(true); } /** Process a click of a button */ public void actionPerformed (ActionEvent e) { boolean b= eastB.isEnabled(); eastB.setEnabled(!b); westB.setEnabled(b); } red: listening blue: placing westB _____ eastB _____ ButtonDemo1() actionPerformed(…) Buttondemo1 a0 JFrame implements ActionListener, defines actionPerformed

11 A JPanel that is painted The content pane has a JPanel in its CENTER and a “reset” button in its SOUTH. The JPanel has a horizontal box b, which contains two vertical Boxes. Each vertical Box contains two instances of class Square. Click a Square that has no pink circle, and a pink circle is drawn. Click a square that has a pink circle, and the pink circle disappears. Click the rest button and all pink circles disappear. This GUI has to listen to: (1) a click on a Button (2) a click on a Square these are different kinds of events, and they need different listener methods

12 Class Square /** An instance is a JPanel of size (WIDTH,HEIGHT). Green or red depending on whether the sum of constructor parameters is even or odd... */ public class Square extends JPanel { public static final int HEIGHT= 70; // height and public static final int WIDTH= 70; // width of square private int x, y; // Coordinates of square on board private boolean hasDisk= false; // = "square has pink disk" /** Constructor: a square at (x,y) */ public Square(int x, int y) { this.x= x; this.y= y; setPreferredSize(new Dimension(WIDTH,HEIGHT)); } /** Complement the "has pink disk" property */ public void complementDisk() { hasDisk= ! hasDisk; repaint(); // Ask the system to repaint the square } continued on next page

13 Class Square /** Remove pink disk (if present) */ public void clearDisk() { hasDisk= false; // Ask system to // repaint square repaint(); } continuation of class Square /* paint this square using g. System calls paint whenever square has to be redrawn.*/ public void paint(Graphics g) { if ((x+y)%2 == 0) g.setColor(Color.green); else g.setColor(Color.red); g.fillRect(0, 0, WIDTH-1, HEIGHT-1); if (hasDisk) { g.setColor(Color.pink); g.fillOval(7, 7, WIDTH-14, HEIGHT-14); } g.setColor(Color.black); g.drawRect(0, 0, WIDTH-1,HEIGHT-1); g.drawString("("+x+", "+y+")", 10, 5+HEIGHT/2); }

14 A class that listens to a mouseclick in a Square import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; /** Contains a method that responds to a mouse click in a Square */ public class MouseEvents extends MouseInputAdapter { // Complement "has pink disk" property public void mouseClicked(MouseEvent e) { Object ob= e.getSource(); if (ob instanceof Square) { ((Square)ob).complementDisk(); } This class has several methods (that do nothing) that process mouse events: mouse click mouse press mouse release mouse enters component mouse leaves component mouse dragged beginning in component Our class overrides only the method that processes mouse clicks red: listening blue: placing

15 Class MouseDemo2 public class MouseDemo2 extends JFrame implements ActionListener { Box b= new Box(BoxLayout.X_AXIS); Box leftC= new Box(BoxLayout.Y_AXIS); Square b00= new Square(0,0); Square b01= new Square(0,1); Box riteC= new Box(BoxLayout.Y_AXIS); Square b10= new Square(1,0); Square b11= new Square(1,1); JButton jb= new JButton("reset"); MouseEvents me= new MouseEvents(); /** Constructor: … */ public MouseDemo2() { super(t); leftC.add(b00); leftC.add(b01); riteC.add(b10); riteC.add(b11); b.add(leftC); b.add(riteC); Container cp= getContentPane(); cp.add(b, BorderLayout.CENTER); cp.add(jb, BorderLayout.SOUTH); jb.addActionListener(this); b00.addMouseListener(me); b01.addMouseListener(me); b10.addMouseListener(me); b11.addMouseListener(me); pack(); setVisible(true); setResizable(false); } public void actionPerformed( ActionEvent e) { b00.clearDisk(); b01.clearDisk(); b10.clearDisk(); b11.clearDisk(); } red: listening blue: placing

16 Class MouseDemo2 public class MouseDemo2 extends JFrame implements ActionListener { Box b= new Box(BoxLayout.X_AXIS); Box leftC= new Box(BoxLayout.Y_AXIS); Square b00= new Square(0,0); Square b01= new Square(0,1); Box riteC= new Box(BoxLayout.Y_AXIS); Square b10= new Square(1,0); Square b11= new Square(1,1); JButton jb= new JButton("reset"); MouseEvents me= new MouseEvents(); /** Constructor: … */ public MouseDemo2() { super(t); leftC.add(b00); leftC.add(b01); b.add(leftC); riteC.add(b10); riteC.add(b11); b.add(riteC); Container cp= getContentPane(); cp.add(b, BorderLayout.CENTER); cp.add(jb, BorderLayout.SOUTH); jb.addActionListener(this); b00.addMouseListener(me); b01.addMouseListener(me); b10.addMouseListener(me); b11.addMouseListener(me); pack(); setVisible(true); setResizable(false); } public void actionPerformed(ActionEvent e) { b00.clearDisk(); b01.clearDisk(); b10.clearDisk(); b11.clearDisk(); } red: listening blue: placing b _____ leftC _____ b00___ b01 ___ riteC ______ b10 ___ b11 ___ jb ______ me __a1___ MouseDemo2() actionPerformed(…) MouseDemo2 a0 JFrame implements ActionListener, defines actionPerformed mouseClicked(…) MouseEvents() mouseClicked(…) MouseEvents a1 MouseInputAdaptor MouseInputAdaptor implements a particular interface, defines mouseClicked Note how a1 is registered as a mouse listener for b00, b01, b10, b11

17 Listening to the keyboard import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AllCaps extends KeyAdapter { JFrame capsFrame= new JFrame(); JLabel capsLabel= new JLabel(); public AllCaps() { capsLabel.setHorizontalAlignment(SwingConstants.CENTER); capsLabel.setText(":)"); capsFrame.setSize(200,200); Container c= capsFrame.getContentPane(); c.add(capsLabel); capsFrame.addKeyListener(this); capsFrame.show(); } public void keyPressed (KeyEvent e) { char typedChar= e.getKeyChar(); capsLabel.setText(("'" + typedChar + "'").toUpperCase()); } 1. Extend this class. 2. Override this method. It is called when a key stroke is detected. 3. Add this instance as a key listener for the frame red: listening blue: placing

18 Listening to the keyboard import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AllCaps extends KeyAdapter { JFrame capsFrame= new JFrame(); JLabel capsLabel= new JLabel(); public AllCaps() { capsLabel.setHorizontalAlignment(SwingConstants.CENTER); capsLabel.setText(":)"); capsFrame.setSize(200,200); Container c= capsFrame.getContentPane(); c.add(capsLabel); capsFrame.addKeyListener(this); capsFrame.show(); } public void keyPressed (KeyEvent e) { char typedChar= e.getKeyChar(); capsLabel.setText(("'" + typedChar + "'").toUpperCase()); } Overriding method. Called when a key stroke is detected. red: listening blue: placing keyPressed() … capsFrame _____ capsLabel ______ allCaps() keyPressed (…) AllCaps a4 KeyAdapter KeyAdaptor implements a particular interface, defines keyPressed