Inner Classes Ancora eventi 2 Design considerations The

  • Slides: 41
Download presentation
Inner Classes Ancora eventi

Inner Classes Ancora eventi

2 Design considerations The most important rule to keep in mind about event listeners

2 Design considerations The most important rule to keep in mind about event listeners that they should execute very quickly. Because all drawing and eventlistening methods are executed in the same thread, a slow eventlistener 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.

3 Low-Level Events and Semantic Events can be divided into two groups: low-level events

3 Low-Level Events and Semantic 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.

4 Listeners/Adapters public class My. Class implements Mouse. Listener {. . . some. Object.

4 Listeners/Adapters public class My. Class implements Mouse. Listener {. . . some. Object. add. Mouse. Listener(this); . . . /* Empty method definition. */ public void mouse. Pressed(Mouse. Event e) { } /* Empty method definition. */ public void mouse. Released(Mouse. Event e) { } /* Empty method definition. */ public void mouse. Entered(Mouse. Event e) { } /* Empty method definition. */ public void mouse. Exited(Mouse. Event e) { } public void mouse. Clicked(Mouse. Event e) {. . . //Event listener implementation goes here. . . } }

5 Listeners/Adapters /* * An example of extending an adapter class instead of *

5 Listeners/Adapters /* * An example of extending an adapter class instead of * directly implementing a listener interface. */ public class My. Class extends Mouse. Adapter {. . . some. Object. add. Mouse. Listener(this); . . . public void mouse. Clicked(Mouse. Event e) { //Event. . . } } listener implementation goes here

6 Inner classes //An example of using an inner class. public class My. Class

6 Inner classes //An example of using an inner class. public class My. Class extends JFrame {. . . some. Object. add. Mouse. Listener( new My. Adapter()); . . . class My. Adapter extends Mouse. Adapter { public void mouse. Clicked(Mouse. Event e){ . . . //Event listener implementation goes here. . . } } }

7 Anonymous Inner classes //An example of using an inner class. public class My.

7 Anonymous Inner classes //An example of using an inner class. public class My. Class extends JFrame {. . . some. Object. add. Mouse. Listener( new Mouse. Adapter () { public void mouse. Clicked(Mouse. Event e){ . . . //Event listener implementation goes here. . . } } ); … }

8 Inner classes An instance of Inner. Class can exist only within an instance

8 Inner classes An instance of Inner. Class can exist only within an instance of Enclosing. Class and it has direct access to the instance variables and methods of its enclosing instance.

9 Anonymous Inner classes //An example of using an inner class. public class My.

9 Anonymous Inner classes //An example of using an inner class. public class My. Class extends JFrame {. . . some. Object. add. Mouse. Listener( new Mouse. Adapter() { public void mouse. Clicked(Mouse. Event e){ . . . //Event listener implementation goes here. . . } } }); . . . }

10 Listeners supported by all Swing components component listener n Listens for changes in

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

11 Altri listeners action caret change document undoable edit item list selection window +

11 Altri listeners action caret change document undoable edit item list selection window + Listeners speciali per componenti specifiche (tree. Node. Expansion, ecc)

Layouts and Graphics

Layouts and Graphics

component - container - layout Un Container contiene [0 o +] Components Il Layout

component - container - layout Un Container contiene [0 o +] Components Il Layout specifica come i Components sono disposti nel Container Un Container è un Component (quindi il contenimento è ricorsivo) Un Component ha una Graphics associata

Layouts Gestione del Layout Vedi anche: http: //java. sun. com/docs/books/tutorial/uiswing/layout/index. html

Layouts Gestione del Layout Vedi anche: http: //java. sun. com/docs/books/tutorial/uiswing/layout/index. html

Layouts

Layouts

Layouts

Layouts

Layouts

Layouts

Layouts http: //java. sun. com/docs/books/tutorial/uiswing/layout/spring. html

Layouts http: //java. sun. com/docs/books/tutorial/uiswing/layout/spring. html

class Yellow. Window package it. unitn. science. prog 2. gui. App; import java. awt.

class Yellow. Window package it. unitn. science. prog 2. gui. App; import java. awt. *; import javax. swing. *; public class Yellow. Window extends JFrame { private JPanel content. Pane; public Yellow. Window() { try { jb. Init(); } catch(Exception e) { e. print. Stack. Trace(); } } private void jb. Init() throws Exception { content. Pane=(JPanel)this. get. Content. Pane(); this. set. Size(new Dimension(400, 300)); content. Pane. set. Background(Color. YELLOW); } }

class App package it. unitn. science. prog 2. gui. App; import javax. swing. *;

class App package it. unitn. science. prog 2. gui. App; import javax. swing. *; import java. awt. *; public class App { JFrame finestra=null; public static void main(String[ ] a){ new App(); } public App() { // aggiungere qui: set look&feel (vedi oltre) this. setup. Graphic. Environment(); }

class App private void setup. Graphic. Environment() { finestra = new Yellow. Window(); //new

class App private void setup. Graphic. Environment() { finestra = new Yellow. Window(); //new My. Window // trova le dimensioni dello schermo e della finestra Dimension screen. Size = Toolkit. get. Default. Toolkit(). get. Screen. Size(); Dimension frame. Size = finestra. get. Size(); // assicurati che la finestra non sia più grande dello schermo if (frame. Size. height > screen. Size. height) frame. Size. height = screen. Size. height; if (frame. Size. width > screen. Size. width) frame. Size. width = screen. Size. width;

class App // centra la finestra nello schermo finestra. set. Location((screen. Size. width -

class App // centra la finestra nello schermo finestra. set. Location((screen. Size. width - frame. Size. width) / 2, (screen. Size. height - frame. Size. height) / 2); // fai in modo che la chiusura della finestra // termini l'applicazione finestra. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE ); // rendi la finestra visibile finestra. set. Visible(true); } }

Border. Layout In Yellow. Window cambio il metodo jb. Init: private void jb. Init()

Border. Layout In Yellow. Window cambio il metodo jb. Init: private void jb. Init() throws Exception { JPanel f=(JPanel)this. get. Content. Pane(); JButton north, south, east, west, center; north = new JButton("North"); east = new JButton("East"); west = new JButton("West"); center = new JButton("Center"); south = new JButton("South"); f. set. Layout(new Border. Layout(2, 2)); f. add(north, Border. Layout. NORTH); f. add(south, Border. Layout. SOUTH); f. add(east, Border. Layout. EAST); f. add(west, Border. Layout. WEST); f. add(center, Border. Layout. CENTER); this. set. Size(300, 300); }

Flow. Layout In Yellow. Window cambio il metodo jb. Init: private void jb. Init()

Flow. Layout In Yellow. Window cambio il metodo jb. Init: private void jb. Init() throws Exception { JPanel f=(JPanel)this. get. Content. Pane(); JButton one, two, three, four, five, six; one = new JButton("one"); two = new JButton("two"); three = new JButton("three"); four = new JButton("four"); five = new JButton("five"); six = new JButton("six"); f. set. Layout(new Flow. Layout()); f. add(one); f. add(six); f. add(five); // attenzione all’ordine! f. add(two); f. add(three); f. add(four); // aggiungo five per la seconda volta: - la prima viene eliminata ! f. add(five); this. set. Size(300, 300); }

Border. Layout In Yellow. Window cambio il metodo jb. Init: private void jb. Init()

Border. Layout In Yellow. Window cambio il metodo jb. Init: private void jb. Init() throws Exception { JPanel f=(JPanel)this. get. Content. Pane(); f. set. Layout(new Grid. Layout(3, 4)); JButton b[]=new JButton[10]; // VETTORE DI 10 BOTTON for (int k=0; k<10; k++){ b[k]=new JButton(); // Integer. to. String(int a) traduce l’intero a in una String b[k]. set. Label(Integer. to. String(k)); f. add(b[k]); } this. set. Size(300, 300); }

Border. Layout In Yellow. Window cambio il metodo jb. Init: private void jb. Init()

Border. Layout In Yellow. Window cambio il metodo jb. Init: private void jb. Init() throws Exception{ JPanel f=(JPanel)this. get. Content. Pane(); Card. Layout cl=new Card. Layout(); f. set. Layout(cl); JPanel p[ ]=new JPanel[5]; Color c[ ]={Color. red, Color. orange, Color. green, Color. blue, Color. pink}; for (int k=0; k<5; k++){ p[k]=new JPanel(); p[k]. set. Background(c[k]); f. add(Integer. to. String(k), p[k]); // il primo parametro è una stringa con la quale riferirsi al componente aggiunto } this. set. Size(300, 300); this. set. Visible(true); while (true) { // ciclo infinito try { Thread. sleep(800); // dormi per 500 millisecondi } catch (Exception e) { } cl. next(f); // richiama il prossimo componente } }

Posizionamento assoluto: Null Layout It's possible to set the layout manager to null: no

Posizionamento assoluto: Null Layout It's possible to set the layout manager to null: no layout control. You might do this to position an object on the display at some absolute coordinates. This is almost never the right approach. Components might have different minimum sizes on different platforms, and your interface would not be very portable. import java. awt. *; public class Applicazione { public static void main(String s[]) {Applicazione a=new Applicazione()} Applicazione() { JFrame g= new JFrame ("Finestra controllata da BORDER Layout"); JPanel f=(JPanel)(g. get. Content. Frame(); f. set. Size(200, 200); // Dimensione della finestra f. set. Location(50, 100); // Posizione della finestra JButton b=new JButton(("Push me"); f. set. Layout(null); f. add(b); b. set. Size(25, 75); // Dimensiono il Bottone b. set. Location(10, 100); // Posiziono il bottone nella finestra g. set. Visible(true); } }

Custom Painting Gestione della Grafica customizzata Vedi anche: http: //java. sun. com/docs/books/tutorial/uiswing/14 painting/index. html

Custom Painting Gestione della Grafica customizzata Vedi anche: http: //java. sun. com/docs/books/tutorial/uiswing/14 painting/index. html

Metodi grafici di Graphics draw. Line() Draws a line draw. Rect() Draws a rectangle

Metodi grafici di Graphics draw. Line() Draws a line draw. Rect() Draws a rectangle fill. Rect() Draws a filled rectangle draw. Round. Rect()Draws a rounded-corner rectangle fill. Round. Rect() Draws a filled, rounded-corner rectangle draw 3 DRect() Draws a highlighted, 3 D rectangle fill 3 DRect() Draws a filled, highlighted, 3 D rectangle draw. Arc() Draws an arc fill. Arc() Draws a filled arc draw. Oval() Draws an oval fill. Oval() Draws a filled oval draw. Polygon() Draws a polygon, connecting endpoints fill. Polygon() Draws a filled polygon draw. Polyline() Draws a line connecting a polygon's points

Il sistema di coordinate

Il sistema di coordinate

import public java. awt. *; javax. swing. *; java. awt. event. *; class Test.

import public java. awt. *; javax. swing. *; java. awt. event. *; class Test. Pattern { public static void main(String[] args) { new Test. Pattern(); } public Test. Pattern() { start. Graphics(); } public void start. Graphics(); { JFrame f = new JFrame("Test. Pattern"); f. set. Size(300, 300); f. set. Content. Pane(new My. Panel()); f. set. Visible(true); } } Disegno Grafico

class My. Panel extends JPanel { int theta = 45; int delta = 90;

class My. Panel extends JPanel { int theta = 45; int delta = 90; public void paint. Component(Graphics g) { super. paint. Component(g); int width = get. Size(). width; int height = get. Size(). height; int h. Width = width / 2; int h. Height = height / 2; int x = (width - h. Width)/2; int y = (height - h. Height)/2; g. set. Color(Color. black); g. fill. Rect(0, 0, size(). width, size(). height); int[] polyx = {0, width / 2, width / 2}; int[] polyy = {height / 2, 0, height / 2, height}; Polygon poly = new Polygon(polyx, polyy, 4); g. set. Color(Color. yellow) g. fill. Polygon(poly); g. set. Color(Color. red); g. fill. Rect(x, y, h. Width, h. Height); g. set. Color(Color. green); g. fill. Oval(x, y, h. Width, h. Height); g. set. Color(Color. blue); g. fill. Arc(x, y, h. Width, h. Height, theta, delta); g. set. Color(Color. white); g. draw. Line(x, y, x + h. Width, x + h. Height); } } Disegno Grafico

Animazione Click!

Animazione Click!

class My. Panel extends JPanel implements Mouse. Listener{ int theta = 45; int delta

class My. Panel extends JPanel implements Mouse. Listener{ int theta = 45; int delta = 90; public void paint. Component(Graphics g) {. . . Animazione } public void mouse. Clicked(Mouse. Event e) { theta=theta-90; this. repaint(); } public void mouse. Entered(Mouse. Event e) {} public void mouse. Exited(Mouse. Event e) {} public void mouse. Pressed(Mouse. Event e) {} public void mouse. Released(Mouse. Event e) {} } My. Panel() {this. add. Mouse. Listener(this); } } Double buffering dietro le quinte!

Repainting NON SI CHIAMA MAI ESPLICITAMENTE LA paint. Component(Graphics g)! [ nè la paint(Graphics

Repainting NON SI CHIAMA MAI ESPLICITAMENTE LA paint. Component(Graphics g)! [ nè la paint(Graphics g) ] Si chiama sempre, solo la repaint() NON SI IMPLEMENTA MAI LA REPAINT! La repaint viene chiamata anche dal sistema quando lo ritiene opportuno (resize, unhide. . . )

class My. Panel extends JPanel implements Mouse. Listener{ public void paint. Component(Graphics g) {

class My. Panel extends JPanel implements Mouse. Listener{ public void paint. Component(Graphics g) { super. paint. Component(g); int rval, gval, bval; Colore for (int j for (int rval = gval = bval = = 30; j < (this. size(). height i = 5; i < (this. size(). width (int)Math. floor(Math. random() -25); j += 30) -25); i+= 30) { * 256); g. set. Color(new Color(rval, gval, bval)); g. fill. Rect(i, j, 25); g. set. Color(Color. black); g. draw. Rect(i-1, j-1, 25); } }. . . } Double buffering dietro le quinte!

Animazione Click! Resize!

Animazione Click! Resize!

Insets protected void paint. Component(Graphics g) {. . . Insets insets = get. Insets();

Insets protected void paint. Component(Graphics g) {. . . Insets insets = get. Insets(); int current. Width = get. Width() - insets. left - insets. right; int current. Height = get. Height() - insets. top - insets. bottom; . . . /* First painting occurs at (x, y), where x is at least insets. left, and y is at least insets. top. */. . . }

Come avviene il “painting” 1. background (if opaque) 2. custom painting (if any) 3.

Come avviene il “painting” 1. background (if opaque) 2. custom painting (if any) 3. border (if any) 4. children (if any) paint. Component — The main method for painting. By default, it first paints the background if the component is opaque. Then it performs any custom painting. paint. Border — Tells the component's border (if any) to paint. Do not invoke or override this method. paint. Children — Tells any components contained by this component to paint themselves. Do not invoke or override this method.

Regole When implementing custom painting code for a component, keep these rules in mind:

Regole When implementing custom painting code for a component, keep these rules in mind: • Your custom painting code should be in a method with the signature protected void paint. Component(Graphics). To gain access to the power of the 2 D graphics API , you can cast the Graphics parameter into a Graphics 2 D object. • You can use a border to paint the outside edges of your component. • Except when painting the background of the component, you should avoid painting over the border area of the component. You can determine this area using the get. Insets method. • Your component must honor the opaque property. If your component is opaque, it must paint its complete area using an opaque color or colors. If its opaque property is false, then you have the option of not painting over the entire component.

class My. Panel extends JPanel { public void paint. Component(Graphics g) { super. paint.

class My. Panel extends JPanel { public void paint. Component(Graphics g) { super. paint. Component(g); Font f = new Font("Times. Roman", Fonts Font. PLAIN, 18); Font. Metrics fm = get. Font. Metrics(f); g. set. Font(f); String s = "This is a plain font"; int xstart = (get. Size(). width – fm. string. Width(s))/2; g. draw. String(s, xstart, 25); Font fb = new Font("Times. Roman", Font. BOLD, 18); Font fi = new Font("Times. Roman", Font. ITALIC, 18); Font fbi=new Font("Times. Roman", Font. BOLD +Font. ITALIC, 18); g. set. Font(fb); g. draw. String("This is a bold font", 10, 50); g. set. Font(fi); g. draw. String("This is an italic font", 10, 75); g. set. Font(fbi); g. draw. String("This is a bold italic font", 100); }. . . }