Review Session for EXCEPTIONS & GUI -Deepak Bapat

Slides:



Advertisements
Similar presentations
Java Software Development Paradigm Lecture # 12. Basics of GUI.
Advertisements

CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Graphical User Interfaces CS 2110 Spring Ivan Sutherland: “Sketchpad”,
CS April 2010 Exceptions in Java. Read chapter 10. HUMOR FOR LEXOPHILES (LOVERS OF WORDS): Police were called to a day care; a three-year-old was.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Scott Grissom, copyright 2006Ch 11: GUI Slide 1 Graphical User Interfaces (Ch 11) Careful design of a graphical user interface is key to a viable software.
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Java Programming Chapter 10 Graphical User Interfaces.
Introduction to GUI Java offers a great number of pre-defined classes to support the development of graphical user interfaces –These are broken down into.
OOP (Java): Layout/ OOP Objectives – –describe the basic layout managers for GUIs Semester 2, GUI Layout.
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: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Review Session for EXCEPTIONS & GUIS -David Gries 1 Adapted from Previous Review Slides.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
CSE 219 Computer Science III Graphical User Interface.
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
Lecture 2 Exception handling Advanced Java Programming 1 dr inż. Wojciech Bieniecki
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.
Object Oriented programming Instructor: Dr. Essam H. Houssein.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
CS April 2010 Exceptions in Java. Read chapter 10. HUMOR FOR LEXOPHILES (LOVERS OF WORDS): Police were called to a day care; a three-year-old was.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
MIT-AITI 2004 – Lecture 16 Introduction to Swing.
GUI Basics. What is GUI? A graphical user interface (GUI) is a type of user interface item that allows people to interact with programs in more ways than.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
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.
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.
1 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 table--...
Basics of GUI Programming Chapter 11 and Chapter 22.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
CS April 2008 Exceptions in Java. Today’s reading: Ch. 10. Next lecture’s reading: Ch 17. (Most) on-duty consultants now identifiable by stylish.
Recitation 3 2D Arrays, Exceptions. 2D arrays 2D Arrays Many applications have multidimensional structures: ●Matrix operations ●Collection of lists ●Board.
Creating a GUI Class An example of class design using inheritance and interfaces.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Graphical User Interface (GUI)
Applets. 9/04/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L12: Applets Slide 2 Applets Usually.
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
Chapter 6 Building Java GUIs. MVC Model View Controller The model passes its data to the view for rendering The view determines which events are passed.
CSE 205 Exam 2 Review By Cheri Thompson and Katherine Kincade.
Review Session for EXCEPTIONS & GUI -Ankur Agarwal 1.
Chapter 14 – Exception Handling
Graphical User Interfaces
2110: GUIS: Graphical User Interfaces
Exceptions: When things go wrong
Recitation 2 Exception handling.
“Form Ever Follows Function” Louis Henri Sullivan
8 April 2008 GUIS —Graphical User Interfaces
Graphical User Interface (GUI) Programming III
CS2110 Lecture 14. GUIS-Layout Spring 2016
Ellen Walker Hiram College
Chapter 13: Advanced GUIs and Graphics
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
GUIS: Graphical User Interfaces
Containers and Components
GUIS: Graphical User Interfaces
2110: GUIS: Graphical User Interfaces
AWT Components and Containers
IFS410: Advanced Analysis and Design
2110: GUIS: Graphical User Interfaces
Steps to Creating a GUI Interface
2110: Announcements Grades for Prelim 1 are now available. You should have received an from Gradescope about accessing them. Regrade requests will.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Advanced GUIs and Graphics
13 April 2010 GUIS: Graphical User Interfaces
Graphical User Interface
Presentation transcript:

Review Session for EXCEPTIONS & GUI -Deepak Bapat Adapted from Previous Review Slides

Exceptions are signals that help may be needed; they can be “handled”. Exception: event that disrupts the normal flow of program execution Throwable Class and Its Subclasses 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? Execution generates an error if a method throws an exception and you have not handled it yet. You may catch the exception and handle it. Refer to Javadoc API specifications. Eg : method charAt inclass String public char charAt(int index) Return the character at the specified index. An index ranges from 0 to length() - 1. …. Throws: IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.

Writing an exception class class MyException extends Exception { public MyException( ) { super(); } public MyException(String msg) { super(msg); public class Test { public void testMethod( ){ throw new MyException( ); Error: Unhandled exception type MyException in testMethod() Probably best to extend RuntimeException

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

What you just saw on the previous page was a try/catch block try/catch statements What you just saw on the previous page was a try/catch block Sometimes voluntary, sometimes java requires you to try/catch or throw (get to throw in a minute) We “try” a series of commands, but if we get an exception we “catch” the exception and do something else int x=0; String s = “java”; try { x = Integer.parseInt(s); x=2; } catch (NumberFormatException e) { x=1; }

Throwing exceptions To throw an exception, you use the command throw <exception> throw new MyException() When an exception is thrown, normal flow of code stops The exception is propagated up function calls If no catch statement is found, java will exit and the error will be displayed /** Illustrate exception handling */ public class Ex { public static void first() { second(); } public static void second() { third(); public static void third() { throw new MyException("mine");

The “throws” clause /** Class to illustrate exception handling */ public class Ex { public static void first() throws MyException { second(); } public static void second() throws MyException { third(); public static void third() throws MyException { throw new MyException("mine");

Call Output Output of Ex.first() Ex.first(); ArithmeticException: mine at Ex.third(Ex.java:14) at Ex.second(Ex.java:9) at Ex.first(Ex.java:5) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(…) at sun.reflect.DelegatingMethodAccessorImpl.invoke(…) at java.lang.reflect.Method.invoke(Method.java:585)

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

Which is better? Using exceptions Using an if-statement public static Object get(Vector v, int i) {      try {         return v.get(i);      } catch (Exception e) {         return null;      } } Using an if-statement public static Object get(Vector v, int i) {      if (i < 0 || v.size() <= i)           return null;      return v.get(i); }

What is wrong with this? try {            int bricksInRow= Integer.valueOf(b[0]);            int brickRows= Integer.valueOf(b[1]);            if (bricksInRow <= 0 || brickRows <= 0)                return; } catch (NumberFormatException nfe) { } BRICKS_IN_ROW= bricksInRow; BRICK_ROWS= brickRows; BRICK_WIDTH= WIDTH / BRICKS_IN_ROW - BRICK_SEP_H;

if (b.length != 2 || b == null) return /** If b is null, doesn't have exactly two elements, or the elements are not        positive integers, DON'T CHANGE ANYTHING.        If b is non-null, has exactly two elements, and they are positive        integers with no blanks surrounding them, then:        Store the first int in BRICKS_IN_ROW, store the second int in BRICK_ROWS,        and recompute BRICK_WIDTH using the formula given in its declaration.         */    private static void fixBricks(String[] b) {        /** Hint. You have to make sure that the two Strings are positive integers.            The simplest way to do that is to use the calls Integer.valueOf(b[0]) and            Integer.valueOf(b[1]) within a try-statement in which the catch block is            empty. Don't store any values in the static fields UNTIL you are sure            that both array elements are positive integers. */        if (b == null || b.length != 2)            return;        try {            int bricksInRow= Integer.valueOf(b[0]);            int brickRows= Integer.valueOf(b[1]);            if (bricksInRow <= 0 || brickRows <= 0)                return;            BRICKS_IN_ROW= bricksInRow;            BRICK_ROWS= brickRows;            BRICK_WIDTH= WIDTH / BRICKS_IN_ROW - BRICK_SEP_H;        } catch (NumberFormatException nfe) {        }    } BAD  if (b.length != 2 || b == null)       return

GUIs Three things are a must know JFrame JPanel Box Each has its own default LayoutManager JFrame – BorderLayout JPanel – FlowLayout Box – BoxLayout

South East West Center North GUIs – JFrame Extend a JFrame implement its functionality or just call a JFrame JFrame frame = new JFrame("FrameDemo"); public class ComponentExample extends JFrame { public ComponentExample(String t) { super(“FrameDemo”); } The default LayoutManager is BorderLayout South East West Center North

GUIs – JFrame Components in a JFrame java.awt: Old package javax.swing: New package Components JButton, Button: Clickable button JLabel, Label: Line of text JTextField, TextField: Field into which the user can type: JTextArea, TextArea: Many-row field into which user can type JPanel, Panel: Used for graphics; to contain other components JCheckBox: Checkable box with a title JComboBox: Menu of items, one of which can be checked JRadioButton: Same functionality as JCheckBox Container: Can contain other components Box: Can contain other components

Basic Components Component Button, Canvas Checkbox, Choice Label, List, Scrollbar TextComponent TextField, TextArea Container JComponent AbstractButton JButton JToggleButton JCheckBox RadioButton JLabel, JList JOptionPane, JPanel JPopupMenu, JScrollBar, JSlider JTextComponent JTextField, JTextArea Component: Something that can be placed in a GUI window. These are the basic ones that one uses in a GUI Note the use of subclasses to provide structure and efficiency. For example, there are two kinds of JToggleButtons, so that class has two subclasses.

Components that can contain other components Box Container JComponent JPanel Panel Applet Window Frame JFrame JWindow java.awt is the old GUI package. javax.swing is the new GUI package. When they wanted to use an old name, they put J in front of it. (e.g. Frame and JFrame) When constructing javax.swing, the attempt was made to rely on the old package as much as possible. So, JFrame is a subclass of Frame. But they couldn’t do this with JPanel.

You can pack up to 5 things, so you might nest JPanels within a JFrame GUIs – BorderLayout Container cp= getContentPane(); JButton jb= new JButton(“Click here”); JLabel jl= new JLabel( “label 2”); cp.add(jb, BorderLayout.EAST); cp.add(jl, BorderLayout.WEST); pack(); setVisible(true); South East West Center North You can pack up to 5 things, so you might nest JPanels within a JFrame

GUIs – JPanel FlowLayout This is another type of container We nest these inside of other windows The default LayoutManager is FlowLayout FlowLayout Place any number of components in a container http://download.oracle.com/javase/tutorial/uiswing/examples/layout/FlowLayoutDemoProject/src/layout/FlowLayoutDemo.java

GUIs – FlowLayout JPanel compsToExperiment = new JPanel(); compsToExperiment.add(new JButton("Button 1")); compsToExperiment.add(new JButton("Button 2")); compsToExperiment.add(new JButton("Button 3")); compsToExperiment.add(new JButton("Long-Named Button 4")); compsToExperiment.add(new JButton("5")); JPanel controls = new JPanel(); controls.add(new JRadioButton(“Left to right”)); controls.add(new JRadioButton(“Right to left”)); controls.add(new JButton(“Apply orientation”)); http://download.oracle.com/javase/tutorial/uiswing/examples/layout/FlowLayoutDemoProject/src/layout/FlowLayoutDemo.java

Boxes use a BoxLayout in which you add components along an axis GUIs – Box public class BoxDemo extends JFrame { /** horizontal Box with 4 buttons in center. */ public BoxDemo() { super("Box demo"); Box b= new Box(BoxLayout.X_AXIS); b.add(new JButton("0")); b.add(new JButton("1")); b.add(new JButton("2")); b.add(new JButton("3")); getContentPane().add(b); } Boxes use a BoxLayout in which you add components along an axis