ancora sugli eventi gestione degli eventi. modello 1.1

37
Ancora sugli Eventi Gestione degli eventi

Upload: sofia-sheehan

Post on 26-Mar-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Ancora sugli Eventi

Gestione deglieventi

Page 2: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Modello 1.1

Event isgenerated for a

component

Listener executessuitable method

Component getsthe event

Event isconsumed

Componentpasses the Event

to Listener

Component has notregistered for that

event classEvent is discarded

Component has registered for that event class

Component

Listener interface

AWTEvent

x

Page 3: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

3

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(); }

Page 4: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

4

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); }

Page 5: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

5

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);

Page 6: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

6

multiListenerDemoJScrollPane 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().getLength());

}}

Page 7: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

7

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().getLength());

}}

Page 8: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

8

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.

Page 9: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

9

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.

Page 10: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

10

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... } }

Page 11: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

11

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 ... }

}

Page 12: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

12

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... } } }

Page 13: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

13

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... } } ); …}

Page 14: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

14

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.

Page 15: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

15

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... }

}});

... }

Page 16: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

16

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 listener (introduced in 1.4)

Listens for mouse wheel movement over the component.

Page 17: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

17

Altri listeners

action caret change document

undoable edit item list

selection window+ Listeners speciali per componenti specifiche

(treeNodeExpansion, ecc)

Page 18: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Fondamenti di Java

Introduzione alla costruzione di GUI Pluggable Look & Feel

Page 19: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Pluggable Look&Feel

Page 20: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Scelta del Look&Feelpublic 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.

Page 21: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Scelta del Look&Feelpublic 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”.

Page 22: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Available Look&Feel"com.sun.java.swing.plaf.gtk.GTKLookAndFeel"

Specifies the GTK+ look and feel. Introduced in release 1.4.2.

"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.

Page 23: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Sezione: Costruttori

Costruttori

Page 24: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Definizione dei costruttori

Se per una classe A non scrivo nessun costruttore, il sistema automaticamente crea il costruttore A();

Se invece definisco almeno un costruttore non void, ad es. A(int s), il sistema non crea il costruttore A();

Page 25: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Definizione dei costruttori

Se B è figlia di A, il costruttore di B come prima cosa invoca A(), a meno che la prima istruzione non sia una super.

B(int k) { super(k)...}

A(int k) { ...}

A() { ...}

B(int k) { ...}

Page 26: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Invocazione dei costruttoripublic class A { public A() { System.out.println("Creo A"); }}public class B extends A { public B() { System.out.println("Creo B"); } public B(int k) { System.out.println("Creo B_int”); }}

Output:Creo ACreo B_int

public static void main(String [] a) { B b=new B(1); }

Page 27: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Invocazione dei costruttoripublic class A { public A(int k) { System.out.println("Creo A"); }}public class B extends A { public B() { System.out.println("Creo B"); } public B(int k) { System.out.println("Creo B_int”); }}

Output:ERRORE !

Perchè ?

public static void main(String [] a) { B b=new B(1); }

Page 28: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Sezione: Modificatori

Abstract e Controllo di accesso

Page 29: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Modificatori: abstract

Classi dichiarate abstract non possono essere istanziate, e devono essere subclassate.

Metodi dichiarati abstract devono essere sovrascritti

Una class non abstract non può contenere abstract metods

Page 30: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Modificatori: visibilità

public visibile da tutti(non def.)visibile da tutti nello stesso packageprotected visibile dalle sottoclassiprivate nascosta da tutti

public class ACorrectClass {

private String aUsefulString;

public String getAUsefulString() {

return aUsefulString; // "get" the value

}

private void setAUsefulString(String s) {

//protected void setAUsefulString(String s) {

aUsefulString = s; // "set" the value

}

}

Uso di metodi “di accesso”:

Page 31: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Matrice degli accessi

Access LevelsSpecifier Class Package Subclass World

private Y N N N

no specifier Y Y N N

protected Y Y Y N

public Y Y Y Y

Vedi anche http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html

Page 32: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Sezione: Upcast - downcast

Upcast & downcast

Page 33: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

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)

Page 34: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

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)

Page 35: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

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: downcast corretto

OK: upcast implicito

Page 36: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

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");} }

NO: downcast illecito (runtime)java.lang.ClassCastException

OK: upcast implicito

Page 37: Ancora sugli Eventi Gestione degli eventi. Modello 1.1

Type conversion - cast

Si può applicare cast SOLO all’interno di unagerarchia di ereditarietà

È consigliabile usare l'operatore instanceof per verificare prima effettuare un downcast

if (staff[1] instanceof Manager) { Manager n = (Manager)staff[1];...

}