Sezione: Upcast - downcast Upcast & downcast. Coercion Una funzione può essere polimorfa senza essere stata disegnata tale intenzionalmente. Sia f una.

Slides:



Advertisements
Similar presentations
Event handling and listeners What is an event? user actions and context event sources and listeners Why should my programs be event- driven? User interaction.
Advertisements

Ancora sugli Eventi Gestione degli eventi. Modello 1.1.
Fondamenti di Java Introduzione alla costruzione di GUI (graphic user interface)
1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while.
Inner Classes Ancora eventi. 2 Design considerations The most important rule to keep in mind about event listeners that they should execute very quickly.
Handling Mouse Events Event-Driven Programming Approccio standard per programmare GUI In contrapposizione al polling offre: - Maggiore flessibilità - Minor.
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Chapter 16 GUI Programming Basics GUI Overview Event-Driven Programming Basics GUI Classes and Packages A Simple Window Program JFrame Class Java Components.
User Interfaces II GUI – Awt, Swing, Web
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
Rectangles moving and responding to the mouse. We want a window with a pile of rectangles in it When we click a rectangle it changes from filled to unfilled.
1 G54PRG Programming Lecture 1 Amadeo Ascó Adam Moore 22 GUI Programming I.
OLD BUSINESS : Lets talk about the next exam Project proposals – Functional Definitions Go over homework – NEW BUSINESS: Chapter 4 today GUIs Assignment.
Graphical User Interfaces
Made with love, by Zachary Langley Applets The Graphics Presentation.
1 cs205: engineering software university of virginia fall 2006 Wimpy Interfaces.
Web Design & Development Lecture 19. Java Graphics 2.
Programming in Java; Instructor:John Punin Graphics and Graphical User Interfaces1 Programming in Java Graphics and Graphical User Interfaces.
Frame Windows A frame object is used to create a graphical frame window. This frame is used to show information in a graphical application. The JFrame.
Mari Göransson - KaU - Datavetenskap - DAVD11 1 Java Event Handling --
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 17 Creating User Interfaces.
Basic Java – Interface design. Understand: How to use TextPad for Java How to define classes and objects How to create a GUI interface How event-driven.
Graphical User Interfaces Java’s AWT and Swing APIs.
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Drawing in a frame – Java GUI
Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
CS18000: Problem Solving and Object-Oriented Programming.
F27SB2 Programming Languages
Graphical User Interfaces, 2D Graphics & Game Programming.
TCU CoSc Programming with Java Handling Events.
Swing: the art of the GUI COMP204, Bernhard Pfahringer.
Event-Driven Programming You might have realized in creating a GUI and clicking on the JButtons that nothing happens Clicking on a JButton causes the JVM.
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.
Event Handling Events and Listeners Timers and Animation.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
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.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Chapter 11 Java AWT Part I: Mouse Events (Optional) Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
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.
Java GUIs and Graphics CNS Outline  Introduction  Events  Components  Layout managers  Drawing  Introduction  Events  Components  Layout.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
For (int i = 1; i
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
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.
UID – Event Handling and Listeners Boriana Koleva
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
CMSC 341 Making Java GUIs Functional. 09/29/2007 CMSC 341 Events 2 More on Swing Great Swing demo at /demos/jfc/SwingSet2/SwingSet2Plugin.html.
Object Oriented Programming.  Interface  Event Handling.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
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 Handling and Listeners in SWING The practice of event handling.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
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.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Event Driven (Asynchronous) Programming. Event handling in Unity Subclass a class that contains event handling methods, and then override those methods.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Events and Event Handling
CompSci 230 S Programming Techniques
A First Look at GUI Applications
CSE 114 – Computer Science I Event Programming
GUI Event Handling Nithya Raman.
Introduction to Event Handling
Web Design & Development Lecture 12
Events, Event Handlers, and Threads
Constructors, GUI’s(Using Swing) and ActionListner
Presentation transcript:

Sezione: Upcast - downcast Upcast & downcast

Coercion Una funzione può essere polimorfa senza essere stata disegnata tale intenzionalmente. Sia f una funzione che prende un argomento di tipo T, e S sia un tipo che può essere automaticamente convertito in T. Allora f può essere detta polimorfa respetto a S e T. float somma(float x, float y) accetta anche somma (3, 3.14) somma(2,3) (coercion di int a float)

public class Test { public static void main(String a[]) { new Test(); } cast Test() { A a; B b = new B(); a=b; a.f1(); a.f2(); } OK: upcast implicito class A { void f1() {System.out.println("f1");} } class B extends A { void f2() {System.out.println("f2");} } class C extends B { void f3() {System.out.println("f3");} } NO: "method f2 not found in class A" (compiler)

public class Test { public static void main(String a[]) { new Test(); } cast Test() { A a; B b = new B(); a=b; a.f1(); ((B)a).f2(); } class A { void f1() {System.out.println("f1");} } class B extends A { void f2() {System.out.println("f2");} } class C extends B { void f3() {System.out.println("f3");} } OK: upcast implicito OK: downcast corretto

public class Test { public static void main(String a[]) { new Test(); } cast Test() { A a; B b = new B(); a=b; a.f1(); ((C)a).f3(); } class A { void f1() {System.out.println("f1");} } class B extends A { void f2() {System.out.println("f2");} } class C extends B { void f3() {System.out.println("f3");} } OK: upcast implicito NO: downcast illecito (runtime) java.lang.ClassCastException

Type conversion - cast Si può applicare cast SOLO allinterno di una gerarchia di ereditarietà È consigliabile usare l'operatore instanceof per verificare prima effettuare un downcast if (staff[1] instanceof Manager) { Manager n = (Manager)staff[1];... }

Ancora sugli Eventi Gestione degli eventi

Modello 1.1

9 multiListenerDemo package listenersdemo; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MultiListener extends JPanel implements ActionListener { JTextArea topTextArea; JTextArea bottomTextArea; JButton button1, button2; JLabel l = null; final static String newline = "\n"; public static void main(String[] args) { createAndShowGUI(); }

10 multiListenerDemo private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("MultiListener"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. JComponent newContentPane = new MultiListener(); frame.setContentPane(newContentPane); //Display the window. frame.pack(); frame.setVisible(true); }

11 multiListenerDemo public MultiListener() { super(new FlowLayout()); l = new JLabel("Cosa sento io:"); add(l); topTextArea = new JTextArea(); topTextArea.setEditable(false); JScrollPane topScrollPane = new JScrollPane(topTextArea); Dimension preferredSize = new Dimension(200, 75); topScrollPane.setPreferredSize(preferredSize); add(topScrollPane); l = new JLabel("Cosa sente la spia:"); add(l); bottomTextArea = new JTextArea(); bottomTextArea.setEditable(false);

12 multiListenerDemo JScrollPane bottomScrollPane = new JScrollPane(bottomTextArea); bottomScrollPane.setPreferredSize(preferredSize); add(bottomScrollPane); button1 = new JButton("Fra Martino campanaro"); add(button1); button2 = new JButton("Dormi tu?"); add(button2); button1.addActionListener(this); button2.addActionListener(this); button2.addActionListener(new Spia(bottomTextArea)); setPreferredSize(new Dimension(400, 300)); } public void actionPerformed(ActionEvent e) { topTextArea.append(e.getActionCommand() + newline); topTextArea.setCaretPosition(topTextArea.getDocument().getLe ngth()); }

13 multiListenerDemo class Spia implements ActionListener { JTextArea myTextArea; public Spia(JTextArea ta) { myTextArea = ta; } public void actionPerformed(ActionEvent e) { myTextArea.append(e.getActionCommand() + MultiListener.newline); myTextArea.setCaretPosition(myTextArea.getDocument().getLe ngth()); }

14 Design considerations The most important rule to keep in mind about event listeners that they should execute very quickly. Because all drawing and event- listening methods are executed in the same thread, a slow event- listener method can make the program seem unresponsive and slow to repaint itself. You might choose to implement separate classes for different kinds of event listeners. This can be an easy architecture to maintain, but many classes can also mean reduced performance. When designing your program, you might want to implement your event listeners in a class that is not public, but somewhere more hidden. A private implementation is a more secure implementation.

15 Low-Level Events and Semantic Events Events can be divided into two groups: low-level events and semantic events. Low-level events represent window-system occurrences or low-level input. Everything else is a semantic event. Examples of low-level events include mouse and key events both of which result directly from user input. Examples of semantic events include action and item events. Whenever possible, you should listen for semantic events rather than low-level events. That way, you can make your code as robust and portable as possible. For example, listening for action events on buttons, rather than mouse events, means that the button will react appropriately when the user tries to activate the button using a keyboard alternative or a look-and-feel-specific gesture.

16 Listeners/Adapters public class MyClass implements MouseListener {... someObject.addMouseListener(this);... /* Empty method definition. */ public void mousePressed(MouseEvent e) { } /* Empty method definition. */ public void mouseReleased(MouseEvent e) { } /* Empty method definition. */ public void mouseEntered(MouseEvent e) { } /* Empty method definition. */ public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) {...//Event listener implementation goes here... } }

17 Listeners/Adapters /* * An example of extending an adapter class instead of * directly implementing a listener interface. */ public class MyClass extends MouseAdapter {... someObject.addMouseListener(this);... public void mouseClicked(MouseEvent e) { //Event listener implementation goes here... } }

18 Inner classes //An example of using an inner class. public class MyClass extends JFrame {... someObject.addMouseListener( new MyAdapter());... class MyAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e){...//Event listener implementation goes here... } }

19 Anonymous Inner classes //An example of using an inner class. public class MyClass extends JFrame {... someObject.addMouseListener( new MouseAdapter () { public void mouseClicked(MouseEvent e){...//Event listener implementation goes here... } ); … }

20 Inner classes An instance of InnerClass can exist only within an instance of EnclosingClass and it has direct access to the instance variables and methods of its enclosing instance.

21 Anonymous Inner classes //An example of using an inner class. public class MyClass extends JFrame {... someObject.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent e){...//Event listener implementation goes here... } } });... }

22 Listeners supported by all Swing components component listener Listens for changes in the component's size, position, or visibility. focus listener Listens for whether the component gained or lost the ability to receive keyboard input. key listener Listens for key presses; key events are fired only by the component that has the current keyboard focus. mouse listener Listens for mouse clicks and mouse movement into or out of the component's drawing area. mouse-motion listener Listens for changes in the cursor's position over the component. mouse-wheel listenermouse-wheel listener (introduced in 1.4) Listens for mouse wheel movement over the component.

23 Altri listeners action caret change document undoable edit item list selection window + Listeners speciali per componenti specifiche (treeNodeExpansion, ecc)

Grafica di Java Introduzione alla costruzione di GUI Pluggable Look & Feel

Scelta del Look&Feel public static void main(String[] args) { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } new SwingApplication(); //Create and show the GUI. } UIManager.getCrossPlatformLookAndFeelClassName() Returns the Java look and feel. UIManager.getSystemLookAndFeelClassName() Specifies the look and feel for the current platform.

Scelta del Look&Feel public static void main(String[] args) { try { UIManager.setLookAndFeel( "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); } catch (Exception e) { } new SwingApplication(); //Create and show the GUI. } UIManager.getSystemLookAndFeelClassName(String s) Specifies the look and feel for the platform described by s.

Available Look&Feel "com.sun.java.swing.plaf.gtk.GTKLookAndFeel" Specifies the GTK+ look and feel. Introduced in release "javax.swing.plaf.metal.MetalLookAndFeel" Specifies the Java look and feel. "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" Specifies the Windows look and feel. Currently, you can use this look and feel only on Microsoft Windows systems. "com.sun.java.swing.plaf.motif.MotifLookAndFeel" Specifies the CDE/Motif look and feel. This look and feel can be used on any platform.