java e la grafica - unict.it€¦ · java 2d api enables assistive technologies, such as screen...

42
1 - lezione 18 - Grafica in Java Linguaggi Corso M-Z - Laurea in Ingegneria Informatica A.A. 2008 – 2009 Alessandro Longheu http://www.diit.unict.it/users/alongheu [email protected] 2 A. Longheu – Linguaggi M-Z – Ing. Inf. 2008-2009 Java e la grafica L’architettura Java è graphics-ready: Package java.awt il primo package grafico (Java 1.0) indipendente dalla piattaforma... o quasi! Package javax.swing Il nuovo package grafico (Java 2; preliminare da Java 1.1.6) scritto esso stesso in Java, realmente indipendente dalla piattaforma Swing definisce una gerarchia di classi che forniscono ogni tipo di componente grafico: finestre, pannelli, frame, bottoni, aree di testo, checkbox, liste a discesa, ecc. Programmazione “event-driven”: non più algoritmi stile input/elaborazione/output, ma reazione agli eventi che l’utente, in modo interattivo, genera sui componenti grafici ascoltatore degli eventi Si può considerare un paradigma di programmazione a sé stante

Upload: others

Post on 20-Aug-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

1

-lezio

ne 1

8 -

Grafica in Java

Linguaggi

Corso

M-Z -Lau

rea in In

gegneria In

formatica

A.A. 2

008 –

2009

Alessa

ndro Lo

ngheu

http

://www.diit.u

nict.it/u

sers/alongheu

alessandro.lon

[email protected]

nict.it

2

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Java e la grafica

�L’a

rchitettu

ra Ja

va è

graphics-re

ady:

�Packa

ge ja

va.awt

�il p

rimo packa

ge grafico

(Java 1.0)

�indipendente dalla piatta

form

a... o

quasi!

�Packa

ge ja

vax.sw

ing

�Il n

uovo packa

ge grafico

(Java 2; p

relim

inare da Ja

va 1.1.6)

�scritto

esso

ste

sso in Java,

realmente indipendente dalla

piatta

form

a

�Swing definisce

una gerarch

ia di cla

ssi che fo

rnisco

no ogni tip

odi

componente grafico

: finestre

, pannelli,

frame, botto

ni,

aree di

testo

, checkb

ox, liste

a disce

sa, e

cc.�

Programmazio

ne “e

vent-d

riven”:

�non più

algoritm

i stile

input/e

laborazio

ne/output, m

a re

azio

ne

agli

eventi

che l’utente,

in modo interattivo

, genera sui

componenti g

rafici

�asco

ltatore degli e

venti

�Si può co

nsid

erare un paradigma di programmazio

ne a sé

stante

Page 2: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

3

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Enables d

evelopers to

easily in

corporate high-quality

2D graphics,

text,

and images in applica

tions and

applets.

Java 2D inclu

des

exte

nsive

APIs

for

generatin

g and se

nding high-quality o

utput to

prin

ting

device

s.

Java 2D API

Enables a

ssistive te

chnologies, su

ch as scre

en re

aders

and Braille

disp

lays, to

get in

form

ation fro

m th

e user

interfa

ce.

Acce

ssibility

API

Give

s any program that uses Swing components

a

choice

of look

and feel.

For example, the same

program ca

n use eith

er th

e Ja

va or th

e W

indows lo

ok

and fe

el. A

s of v1

.4.2, th

e Ja

va platfo

rm su

pports th

e

GTK+ look a

nd fe

el, w

hich

makes h

undreds o

f existin

g

look a

nd fe

els a

vailable to

Swing programs.

Pluggable

Look-a

nd-Feel

Support

Inclu

des everyth

ing fro

m butto

ns to split

panes to

tables.

Swing

GUI

Components

Features of th

e Java Foundation Classes

Java e la grafica

: JFC

4

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Allows d

evelopers to

build applica

tions th

at ca

n in

teract

with

users w

orld

wide in

their o

wn la

nguages a

nd cu

ltural

conventions.

With

the

input

method

framework

developers

can build applica

tions

that acce

pt text

in

languages th

at u

se th

ousands o

f diffe

rent ch

aracte

rs, such

as Ja

panese, C

hinese, o

r Korean.

I18N

Provid

es

the ability

to drag and drop between Java

applica

tions a

nd native

applica

tions.

Drag-and-Drop

Support

Features of th

e Java Foundation Classes

Java e la grafica

: JFC

�In re

lease 1.4 of th

e Ja

va platfo

rm, th

e Swing API h

as 1

7 public

packa

ges

�Fortu

nately, m

ost p

rograms u

se only a

small su

bset o

f the API:

�javax.sw

ing

�javax.sw

ing.event (n

ot a

lways re

quired)

Page 3: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

5

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

JFC Swing: p

anoramica

6

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

JFC Swing: p

anoramica

Page 4: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

7

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

JFC Swing: p

anoramica

8

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

JFC Swing: p

anoramica

Page 5: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

9

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

JFC Swing: p

anoramica

10

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

JFC Swing: p

anoramica

Page 6: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

11

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

JFC Swing: p

anoramica

12

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

JFC Swing: p

anoramica

Page 7: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

13

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Swing provid

es th

ree generally u

seful to

p-le

vel co

ntainer cla

sses:

JFrame, JDialog, and JApplet.

When usin

g these cla

sses,

you

should keep th

ese facts in mind:

�To appear o

n th

e scre

en, e

very G

UI co

mponent m

ust b

e part o

f a

containment hierarchy. A containment hierarch

y is

a tre

e of

components th

at h

as a

top-le

vel co

ntainer a

s its root.

�Each GUI component can be contained only once. If

a

component is a

lready in

a co

ntainer a

nd yo

u try to

add it to

one

another, it is re

moved fro

m th

e first a

nd added to

the se

cond one.

�Each to

p-le

vel co

ntainer h

as a

content pane th

at co

ntains th

e

visible co

mponents in

that co

ntainer's G

UI.

�You ca

n optionally a

dd a m

enu bar to

a to

p-le

vel co

ntainer. T

he

menu bar

is by

convention positio

ned with

in the top-le

vel

container,

but outsid

e the content pane. Some look and feels,

such as th

e M

ac O

S lo

ok a

nd fe

el, g

ive yo

u th

e option of p

lacin

gthe m

enu bar in

another p

lace m

ore appropriate fo

r the lo

ok a

nd

feel, su

ch as a

t the to

p of th

e scre

en.

JFC Swing: p

anoramica

14

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Each to

p-level containerrelies o

n a re

clusive

interm

ediate co

ntainer

called th

e ro

ot p

ane. T

he ro

ot p

ane m

anages th

e co

ntent p

ane and th

e

menu bar, a

long w

ith a co

uple of o

ther co

ntainers. Y

ou generally

don't

need to

know about ro

ot p

anes to

use Swing co

mponents. H

owever, if

you ever

need to interce

pt

mouse clicks

or

paint

over

multip

le

components, yo

u sh

ould get a

cquainted w

ith ro

ot p

anes. A

root p

ane

consists o

f:

JFC Swing: p

anoramica

Page 8: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

15

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�The glass pane

�Hidden, b

y default. If yo

u m

ake th

e glass p

ane visib

le, th

en it's like

a

sheet of glass

over all

the other parts

of the root pane. It's

completely

transparent

unless

you implement

the glass

pane's

paintComponent m

ethod so

that it d

oes so

mething, a

nd it in

terce

pts

input e

vents fo

r the ro

ot p

ane.

�The layered pane

�Serve

s to positio

n its co

ntents, w

hich

consist o

f the co

ntent p

ane and

the optional m

enu bar. C

an also

hold other co

mponents in

a sp

ecifie

d

Z order.

�The content pane

�The co

ntainer o

f the ro

ot p

ane's visib

le co

mponents, e

xcluding th

e

menu bar.

�The optional m

enu bar

�The home fo

r the ro

ot p

ane's co

ntainer's m

enus. If th

e co

ntainerhas

a m

enu bar, yo

u generally u

se th

e co

ntainer's se

tJMenuBar m

ethodto

put th

e m

enu bar in

the appropriate place.

�Alth

ough the example uses a JFrame, the same concepts

apply

to

JApplets a

nd JD

ialogs.

JFC Swing: p

anoramica

16

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Most n

oncontainer S

wing co

mponents h

ave models. A

butto

n (JB

utto

n),

for e

xample, h

as a

model (a

Butto

nModel object) th

at sto

res th

e butto

n's

state —

what its ke

yboard m

nemonic is, w

hether it's e

nabled, se

lecte

d,

or p

resse

d, a

nd so

on. S

ome co

mponents h

ave m

ultip

le m

odels. A

list (JList), fo

r example, u

ses a

ListModel to

hold th

e list's co

ntents, a

nd a

ListSelectio

nModel to tra

ck the list's cu

rrent se

lectio

n. Y

ou ofte

n don't

need to

know about th

e m

odels th

at a

component u

ses. F

or e

xample,

programs th

at u

se butto

ns u

sually d

eal d

irectly w

ith th

e JB

utto

nobject,

and don't d

eal at a

ll with

the Butto

nModel object.

�Why th

en do m

odels e

xist? The biggest re

ason is th

at th

ey give you

flexibility

in determ

ining how data is stored and re

trieved. F

or

example, if yo

u're desig

ning a sp

readsheet a

pplica

tion th

at d

isplays d

ata

in a sp

arse

ly populated ta

ble, yo

u ca

n cre

ate yo

ur o

wn ta

ble m

odel th

at

is optim

ized fo

r such use.

�Models

have other benefits,

too. Models automatically propagate

changes to

all in

terested lis

teners, m

aking it e

asy for th

e GUI to

stay in sync with

the data. F

or e

xample, to

add ite

ms to

a list yo

u ca

n

invoke m

ethods o

n th

e list m

odel. W

hen th

e m

odel's d

ata ch

anges,

the

model fire

s events to

the JList a

nd any o

ther liste

ners, a

nd th

eGUI is

updated acco

rdingly.

JFC Swing: p

anoramica

Page 9: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

17

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Exce

pt for top-le

vel containers,

all

Swing components

whose

names b

egin with

"J" desce

nd fro

m th

e JComponent class.

�The JComponent cla

ss exte

nds the Container cla

ss, which

itse

lf exte

nds Component.

The Component cla

ss inclu

des everyth

ing

from provid

ing layout h

ints to

supportin

g paintin

g and events. T

he

Container

class

has

support

for

adding components

to the

container a

nd layin

g th

em out.

�The JC

omponent cla

ss provid

es th

e fo

llowing fu

nctio

nality :

�Tool tip

s (string fo

r mouse over co

mponent)

�Paintin

g insid

e a co

mponent a

nd borders m

anagement

�Applica

tion-wide pluggable look a

nd fe

el

�Custo

m propertie

s can be defined

�Support fo

r layout

�Support fo

r acce

ssibility

�Support fo

r drag and drop

�Double buffe

ring (p

rovid

e sm

ooths o

n-scre

en paintin

g)

�Key b

indings(provid

e re

actio

ns w

hen ke

yboard is u

sed)

JFC Swing: p

anoramica

18

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�La piùsemplice applicazione graficaconsiste

in una cla

sse il

cui m

ain cre

a un JF

rame e lo re

nde visib

ile co

l metodo sh

ow():

import java.aw

t.*; im

port javax.sw

ing.*;

public class E

sSwing1 {

public static void

main

(Strin

g[] v){

JFrame f =

new

JFrame("E

sempio 1

");f.sh

ow(); //m

ostra il JFrame

} } �

I comandi sta

ndard delle fin

estre

sono giàattivi

�la ch

iusura nasco

nde so

ltanto il fra

me. P

er ch

iuderlo

serve

Ctrl+

C�

Per im

posta

re le

dimensio

ni d

i un qualunque co

ntenitore si u

sa

setSize

(), che ha co

me parametro

un opportu

no oggetto

di cla

sse

Dimensio

n:

�f.se

tSize

(new Dimensio

n(300,150)); // le

misu

re x,y so

no in pixe

l �

Inoltre

, la fin

estra

viene visu

alizza

ta nell'a

ngolo su

perio

re sin

istro

dello sch

erm

o Per

imposta

re la posizio

ne di un qualunque

contenitore si u

sa se

tLocation():

�f.se

tLocation(200,100)); // (0

,0) =

angolo su

perio

re sin

istro

Frame

Page 10: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

19

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Posizio

ne e dimensio

ni si p

osso

no anche fissa

re in

sieme, co

l metodo se

tBounds()

�esempio di fin

estra

già

dimensio

nata e co

llocata nel p

unto

previsto

:

import java.aw

t.*;

import javax.sw

ing.*;

public class E

sSwing1 {

public static vo

id m

ain(Strin

g[] v){

JFrame f =

new

JFrame("E

sempio 1

");f.setB

ounds(2

00,100, 3

00,150)

f.show();

} }

Frame

20

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Un approccio

effica

ce co

nsiste

nell'estendere JFrame, d

efinendo

una nuova cla

sse:

import java.aw

t.*;

import javax.sw

ing.*;

public class M

yFrame exten

ds JFram

e { public M

yFrame(S

tring titolo){

super(titolo);

setBounds(2

00,100,300,150);

} } import java.aw

t.*; im

port javax.sw

ing.*;

public class E

sSwing2 {

public static void

main

(Strin

g[] v){

MyFram

e f = new

MyFram

e("Esem

pio 2

"); f.sh

ow();

} }

Frame

Page 11: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

21

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�In Swing non si

posso

no aggiungere nuovi

componenti d

iretta

mente al Jfra

me

�Però dentro

ogni JFrame c’è

un Container,

recuperabile co

l metodo getContentPane(): è

a

lui ch

e va

nno aggiunti i n

uovi co

mponenti

�Tipica

mente, si a

ggiunge un pannello (u

n JP

anel

o una nostra

versio

ne più

specifica

), tramite il

metodo add()

�sul

pannello

si può

dise

gnare

(form

e,

immagini...)

o aggiungere pulsa

nti,

etich

ette

, ico

ne, (cio

èaggiungere altri co

mponenti)

Frame

22

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Aggiunta di un pannello

al C

ontainer d

i un fra

me, tra

mite l'u

so

di getContentPane():

import java.aw

t.*;

import javax.sw

ing.*;

public class E

sSwing3 {

public static void

main

(Strin

g[] v){

MyFram

e f = new

MyFram

e("Esem

pio 3

");Contain

er c = f.g

etConten

tPane();

JPanel p

anel =

new

JPanel();

c.add(panel);

f.show

(); }

} �NOTA: n

on abbiamo dise

gnato niente, n

éaggiunto co

mponenti,

sul pannello! Però, avendo, il pannello, potre

mmo usarlo

per

dise

gnare e inserire

altri co

mponenti!

Frame & Panel

Page 12: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

23

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Per disegnare su un pannello

occo

rre:

�definire una propria cla

sse (M

yPanel) ch

e este

nda JP

anel

�rid

efinire paintComponent(),

che è

il metodo (ereditato da

JComponent) ch

e si o

ccupa di dise

gnare il co

mponente

�ATTENZIONE: il n

uovo paintComponent() d

eve se

mpre rich

iamare

il metodo paintComponent() o

riginale, tra

mite su

per

�Il n

ostro

pannello perso

nalizza

to:

public class M

yPanel exten

ds JP

anel {

// nessu

n co

struttore, va b

ene il d

efault

public void

pain

tComponent(G

raphics g

){ super.p

aintCom

ponent(g

); // q

ui ag

giungerem

o le nostre istru

zioni di diseg

no…

} }

�Graphics

g, di cui non ci

dobbiamo occu

pare esplicita

mente, è

l'oggetto

del siste

ma che effe

ttivamente dise

gna ciò

che gli

ordiniamo

Panel

24

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Quali m

etodi per d

isegnare?

�drawIm

age(), d

rawLin

e(), d

rawRect(),

drawRoundRect(), d

raw3DRect(), d

rawOval(),

drawArc(), d

rawStrin

g(), d

rawPolyg

on(),

drawPolyLin

e()

�fillR

ect(), fillR

oundRect(), fill3

DRect(), fillO

val(),

fillArc(), fillP

olyg

on(), fillP

olyLin

e()

�getColor(), g

etFont(), se

tColor(), se

tFont(),

copyArea(), cle

arRect()

Panel

Page 13: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

25

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Il p

annello perso

nalizza

to co

n il d

isegno:

import java.aw

t.*;

import javax.sw

ing.*;

public class M

yPanel exten

ds JP

anel {

public vo

id pain

tCom

ponent(G

raphics g

){ super.p

aintComponent(g

); g.setC

olor(C

olor.red

); // white, g

ray, lightGray

g.fillR

ect(20,20, 1

00,80);

g.setC

olor(C

olor.b

lue);

g.draw

Rect(3

0,30, 8

0,60);

g.setC

olor(C

olor.b

lack); g.draw

Strin

g("ciao

",50,60);

} } P

anel

26

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Il m

ain ch

e lo cre

a e lo inserisce

nel fra

me:

import java.aw

t.*;

import javax.sw

ing.*;

public class E

sSwing4 {

public static vo

id m

ain(Strin

g[] v){

MyFram

e f = new

MyFram

e("Esem

pio 4");

// potrem

mo an

che u

sare un JFram

e standard

…Contain

er c = f.g

etConten

tPane();

MyPanel p

anel =

new

MyPanel();

c.add(panel);

f.show();

} }

Panel

Page 14: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

27

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Per ca

mbiare fo

nt, si cre

a un oggetto

Font a

ppropriato, lo

si

imposta

come font

predefinito usando il

metodo

setFont()

Font f1

= new

Font("T

imes", Fon

t.BOLD

, 20);

// nome d

el font, stile, d

imension

e in punti

// stili possib

ili: Font.P

LAIN, Fon

t.ITALIC

g.setFon

t(f1);

�Recuperare le proprietà

di un font:

il font corre

nte si

recupera con getFont(),

mentre

le sue proprietà

si recuperano con getName(),

getStyle

(), getSize

() e si

verifica

no co

n i p

redica

ti isPlain(), isB

old(), isIta

lic(): Font f1

= g.getFo

nt();

int size =

f1.getS

ize(); int style =

f1.getS

tyle(); Strin

g nam

e = f1.g

etNam

e();

Panel

28

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Esempio di grafico di una funzione:

�occo

rre cre

are un'apposita

cla

sse Functio

nPanel che este

nda

JPanel, rid

efinendo il m

etodo paintComponent() co

me appropriato,

ad esempio:

�sfo

ndo bianco, co

rnice

nera

�assi ca

rtesia

ni ro

ssi, con estre

mi in

dica

ti �funzio

ne dise

gnata in blu

�cre

are, n

el m

ain, u

n oggetto

di tip

o Functio

nPanel

�Definizio

ne del so

lito m

ain:

import java.aw

t.*;

import javax.sw

ing.*;

public class E

sSwing5 {

public static void

main

(Strin

g[] v){

JFrame f =

new

JFrame("G

rafico f(x)");

Contain

er c = f.g

etConten

tPane();

Functio

nPanel p

= new

Functio

nPanel(); c.ad

d(p);

f.setBounds(1

00,100,500,400);

f.show

(); } }

Panel

Page 15: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

29

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Definizio

ne del pannello apposito

: �cla

ss Functio

nPanel exte

nds JP

anel {

int xM

in=-7, xM

ax=7, yM

in=-1, yM

ax=1;

// gli in

tervalli in cu

i vogliam

o graficare

int larg

hezza=

500, altezza=

400;

// corrisp

ondono alla g

randezza d

el Jframe

float fatto

reScalaX

, fattoreS

calaY;

public vo

id pain

tCom

ponent(G

raphics g

){ super.p

aintComponent(g

); setB

ackground(Color.w

hite);

fattoreS

calaX=larg

hezza/((flo

at)xMax-xM

in);

fattoreS

calaY=altezza/((flo

at)yMax-yM

in);

g.setC

olor(C

olor.b

lack);

Panel

30

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

g.draw

Rect(0

,0,larg

hezza-1

,altezza-1);

g.setC

olor(C

olor.red

); g.draw

Line(0

,altezza/2, larg

hezza-1

,altezza/2);

g.draw

Line(larg

hezza/2

,0,larg

hezza/2

,altezza-1);

g.draw

Strin

g(""+

xMin, 5

,altezza/2-5);

g.draw

Strin

g(""+

xMax, larg

hezza-1

0,altezza/2

-5);

g.draw

Strin

g(""+

yMax, larg

hezza/2

+5,15);

g.draw

Strin

g(""+

yMin, larg

hezza/2

+5,altezza-5

); �Contin

ua…..

Panel

Page 16: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

31

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

// diseg

na il g

rafico della fu

nzio

ne in

blu

g.setC

olor(C

olor.b

lue); setP

ixel(g,xM

in,f(xM

in));

// punto iniziale

for (in

t ix=1; ix<

larghezza; ix+

+){ // p

er ognuno dei p

ixel della fin

estra float x =

xMin+((float)ix)/fatto

reScalaX

; setPixel(g

,x,f(x)); }

} // d

efinizio

ne d

ella funzio

ne, statica, d

a graficare

static float f(flo

at x){ return (flo

at)Math

.sin(x);

} // q

uesta serve p

er riportare i valo

ri della fu

nzio

ne su

i valorid

ella finestra

void setP

ixel(Grap

hics g

, float x, flo

at y){ if (x<

xMin || x>

xMax || y<

yMin || y>

yMax ) retu

rn;

int ix =

Math

.round((x-xM

in)*fatto

reScalaX

); int iy =

altezza-Math

.round((y-yM

in)*fatto

reScalaY

); g.draw

Line(ix,iy,ix,iy);

// diseg

na in

effetti un sin

golo punto

} } Panel

32

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Panel

�Risu

ltato:

Page 17: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

33

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Come si

dise

gna un'im

magine presa da un

file?

�ci si p

rocura un apposito

oggetto

Image

�si re

cupera il "to

olkit d

i default":

Toolkit tk =

Toolkit.g

etDefau

ltToolkit();

�si ch

iede al to

olkit d

i recuperare l'im

magine:

Image im

g = tk.g

etImage("n

ew.gif");

�Sono su

pporta

ti i form

ati G

IF e JP

EG

�Si può anche fo

rnire un URL:

URL u

rl = ...;

Image im

g = tk.g

etImage(u

rl);

Toolkit

34

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�si d

isegna l'im

magine co

n drawIm

age()

�PROBLEMA: d

rawIm

age() rito

rna al ch

iamante su

bito

dopo aver in

iziato il ca

ricamento dell'im

magine, se

nza

atte

ndere di

averla carica

ta.

C'è

il risch

io che

l'immagine non fa

ccia in

tempo a visu

alizza

rsi prim

a

della fin

e del programma.

�SOLU

ZIONE:

si cre

a un oggetto

MediaTracke

r dedica

to ad occu

parsi d

el ca

ricamento dell'im

magine

MediaTracke

r

Page 18: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

35

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Uso del M

ediaTracke

r�

1) N

el co

strutto

re del p

annello, si cre

a un oggetto

MediaTracke

r, precisa

ndogli su

quale co

mponente avve

rràil d

isegno (d

i solito

il parametro

èthis, il p

annello ste

sso)

MediaT

racker mt =

new

MediaT

racker(this);

�2) ...si a

ggiunge l'im

magine al M

ediaTracke

r...mt.ad

dIm

age(im

g,1);

�Il secondo parametro

èun numero in

tero, a

nostra

scelta,

che identifica

univo

camente l'im

magine.

�3) ...e

gli si d

ice di a

ttendere il ca

ricamento di ta

le im

magine,

usando il n

umero intero (ID

) da noi asse

gnato

try { mt.w

aitForID(1); }

catch (In

terrupted

Excep

tion e) {}

�Se si d

evono atte

ndere m

olte im

magini:

try { mt.w

aitForAll(); }

catch (In

terrupted

Excep

tion e) {}

MediaTracke

r

36

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

public class Im

gPanel exten

ds JP

anel {

Image im

g1;

public Im

gPanel(){

Toolkit tk =

Toolkit.g

etDefau

ltToolkit();

img1 = tk.g

etImage("n

ew.gif");

MediaT

racker mt =

new

MediaT

racker(this);

mt.ad

dIm

age(im

g1, 1);

// aggiunta d

i eventuali altre im

magini

try { mt.w

aitForAll(); }

catch (In

terrupted

Excep

tion e){}

}public vo

id pain

tComponent(G

raphics g

){super.p

aintComponent(g

);g.draw

Image(im

g1, 30, 3

0, null);

/* Im

magine (im

g1), p

osizione n

el pannello

(30,30

) e un oggetto

(null, cio

ènessu

no) a cu

i notificare l'avven

uto caricam

ento */

}}

Toolkit &

MediaTracke

r

Page 19: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

37

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Oltre

a dise

gnare, dentro

ai pannelli

si posso

no inserire

altre

componenti, a

d esempio una JLa

bel:

import java.aw

t.*; im

port javax.sw

ing.*;

public class E

sSwing7 {

public static void

main

(Strin

g[] v){

JFrame f =

new

JFrame(”E

sempio 7

");Contain

er c = f.g

etConten

tPane();

Es7Panel p

= new

Es7Panel();

c.add(p);

f.pack(); //p

ack dimension

a il frame

f.show

();}}public class E

s7Panel exten

ds JP

anel {

public E

s7Panel(){

super();

JLabel l =

new

JLabel("E

tichetta");

add(l);}}

Components

38

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Careful use of concurre

ncy

is particu

larly

importa

nt to the Swing

programmer. A

well-w

ritten Swing program uses co

ncurre

ncy to

create a

user in

terfa

ce th

at n

ever "fre

ezes" —

the program is a

lways re

sponsive

to user in

teractio

n, n

o m

atte

r what it's d

oing.

�A Swing programmer d

eals w

ith th

ree kinds of th

reads:

�Initia

l threads, th

e th

reads th

at e

xecute initia

l applica

tion co

de.

�The event d

ispatch th

read, w

here all e

vent-h

andling co

de is e

xecuted.

Most co

de th

at in

teracts w

ith th

e Swing fra

mework m

ust a

lso execute on

this th

read.

�Worker threads, also

known as

backg

round threads,

where tim

e-

consuming backg

round ta

sks are executed.

�The programmer d

oes n

ot n

eed to

provid

e co

de th

at e

xplicitly cre

ates

these th

reads: th

ey a

re provid

ed by th

e ru

ntim

e or th

e Swing fra

mework.

The programmer's jo

b is to

utilize

these th

reads to

create a re

sponsive

, maintainable Swing program.

�Like

any o

ther p

rogram ru

nning on th

e Ja

va platfo

rm, a

Swing program

can cre

ate additio

nal th

reads B

ut fo

r basic S

wing programs th

e th

reads

describ

ed here are su

fficient.

Swing & th

read

Page 20: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

39

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Every p

rogram has a

set o

f threads w

here th

e applica

tion logic b

egins.

�In sta

ndard programs, th

ere's o

nly o

ne su

ch th

read: th

e th

read th

at

invokes th

e m

ain m

ethod of th

e program cla

ss. �

In applets th

e in

itial th

reads a

re th

e ones th

at co

nstru

ct the applet

object a

nd in

voke its in

it and sta

rt methods; th

ese actio

ns m

ay o

ccur

on a sin

gle th

read, o

r on tw

o or th

ree diffe

rent th

reads, d

epending on

the Ja

va platfo

rm im

plementation.

�These th

reads a

re ca

lled th

e in

itial threads. In

Swing programs, th

e

initia

l threads d

on't h

ave a lot to

do. T

heir m

ost e

ssential jo

bis to

create

a Runnable object th

at in

itialize

s the G

UI a

nd sch

edule th

at o

bject fo

r execution on th

e event d

ispatch

thread.

�Once th

e GUI is cre

ated, th

e program is p

rimarily d

riven by G

UI e

vents,

each of w

hich

causes th

e execution of a

short ta

sk on th

e event d

ispatch

thread.

�Applica

tion code can sch

edule additio

nals

tasks

on th

e event disp

atch

thread (if

they

complete quickly,

so as not to interfe

re with

event

processin

g) o

r a worke

r thread (fo

r long-ru

nning ta

sks).

Swing & th

read

40

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�An initia

l thread

schedules

the GUI

creation task

by

invokin

g

javax.swing.SwingUtilities.in

vokeLater

or

javax.swing.SwingUtilities.in

vokeA

ndWait. B

oth of th

ese m

ethods ta

ke a

single argument:

the Runnable that defines the new task.

Their

only

diffe

rence is in

dica

ted by th

eir n

ames: in

vokeLater sim

ply sch

edules th

e

task

and returns;

invokeAndWait

waits

for the task

to finish

before

returning.

�In an applet,

the GUI-cre

ation task

must

be launched fro

m the init

method usin

g in

vokeAndWait; o

therwise

, init m

ay re

turn before th

e GUI

is created, w

hich

may ca

use problems fo

r a browser la

unching an applet.

�In an application, sch

eduling th

e GUI-cre

ation ta

sk is usually th

e la

st thing the initia

l thread does,

so it

doesn't

matte

r whether it

uses

invokeLater o

r invokeAndWait.

�Why doesn't

the initia

l thread sim

ply

create the GUI itse

lf? Because

almost a

ll code th

at cre

ates o

r interacts w

ith Swing co

mponents m

ust ru

n

on th

e event d

ispatch

thread. T

his re

striction is d

iscusse

d fu

rther la

ter.

Swing & th

read

Page 21: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

41

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Swing event h

andling co

de ru

ns o

n a sp

ecia

l thread kn

own as th

e event

dispatch th

read. M

ost co

de th

at in

vokes S

wing m

ethods a

lso ru

ns o

n

this th

read. T

his is n

ecessa

ry because m

ost S

wing object m

ethodsare

not "th

read safe":

invokin

g them fro

m multip

le threads risks

thread

interfe

rence

or memory

consiste

ncy

erro

rs. Some Swing component

methods a

re labelled "th

read sa

fe" in

the API sp

ecifica

tion; th

ese ca

n be

safely

invoked fro

m any thread. All other Swing component methods

must b

e in

voked fro

m th

e event d

ispatch

thread. P

rograms th

at ig

nore

this

rule may functio

n corre

ctly most

of the tim

e, but are subject

to

unpredicta

ble erro

rs that a

re difficu

lt to re

produce.

�It's u

seful to

think o

f the co

de ru

nning on th

e event d

ispatch

thread as a

series

of short

tasks.

Most

tasks

are invocations

of event-h

andling

methods,

such as Actio

nListen

er.actionPerfo

rmed. Other tasks

can be

scheduled by a

pplica

tion co

de, u

sing invokeLater o

r invokeAndWait.

�Tasks

on the event disp

atch

thread must

finish

quickly;

if they don't,

unhandled events b

ack u

p and th

e user in

terfa

ce becomes u

nresponsive

.

Swing & th

read

42

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�When a Swing program needs to

execute a lo

ng-ru

nning ta

sk, it usually

uses one of the worker threads, also

known as the

backg

round threads.

Each task

running on a worke

r thread is

represented

by

an

insta

nce

of

javax.sw

ing.SwingWorke

r. SwingWorke

r itself is a

n abstra

ct class; yo

u m

ust d

efine a su

bcla

ss in order to

create a SwingWorke

r object. S

wingWorke

r provid

es

the fo

llowing fe

atures:

�SwingWorke

r can define a m

ethod, d

one, w

hich

is automatica

lly invoked on th

e event d

ispatch

thread when th

e backg

round ta

sk isfinish

ed.

�SwingWorke

r implements

java.util.con

curren

t.Future.

This

interfa

ce allows th

e backg

round ta

sk to provid

e a re

turn va

lue to

the other th

read. O

ther m

ethods in

this in

terfa

ce allow ca

ncellation

of th

e backg

round ta

sk and disco

verin

g w

hether th

e backg

round

task h

as fin

ished or ca

ncelled.

Swing & th

read

Page 22: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

43

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�The backg

round ta

sk can provid

e interm

ediate re

sults

by

invokin

g SwingWorker.p

ublish

, causin

g SwingWorker.p

rocess

to be invoked fro

m th

e event d

ispatch

thread.

�The backg

round ta

sk can define bound propertie

s. Changes

to these propertie

s trig

ger events,

causin

g event-h

andling

methods to

be invoked on th

e event d

ispatch

thread.

�The ja

vax.sw

ing.SwingWorke

r class w

as a

dded to

the Ja

va

platfo

rm in

Java SE 6. P

rior to

this, a

nother cla

ss, also

called

SwingWorke

r, was

widely

used for

some of the same

purposes.

The old SwingWorke

r was not part

of the Java

platfo

rm sp

ecifica

tion, a

nd w

as n

ot p

rovid

ed as p

art o

f the

JDK. Swing & th

read

44

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Let's start

with

an example

of a very

simple but tim

e-

consuming ta

sk. The TumbleItem

applet lo

ads a

set o

f graphic

files u

sed in

an animation. If th

e graphic file

s are lo

aded fro

man

initia

l thread, th

ere m

ay b

e a delay b

efore th

e GUI a

ppears. If th

e

graphic file

s are lo

aded fro

m th

e event d

ispatch

thread, th

e GUI

may

be temporarily

unresponsive

. To avoid these problems,

TumbleIte

m executes a

n in

stance of S

wingWorke

r from its in

itial

threads.

�The object's

doInBackg

round method, executin

g in a worke

r thread, lo

ads th

e im

ages in

to an Im

ageIco

n arra

y, and re

turns a

reference to

it. �

Then th

e done m

ethod, e

xecutin

g in

the event d

ispatch

thread,

invokes g

et to

retrie

ve th

is reference, w

hich

it assig

ns to

to an

applet

class

field named imgs.

This

allows

TumbleIte

m to

constru

ct the GUI immediately,

with

out waitin

g for images to

finish

loading.

Swing & th

read

Page 23: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

45

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

SwingWorker w

orker =

new

SwingWorker() {

@Overrid

e public Im

ageIco

n[] d

oInBackg

round() {

final Im

ageIco

n[] in

nerIm

gs =

new

ImageIco

n[nimgs];

for (in

t i = 0; i <

nimgs; i+

+) { in

nerIm

gs[i] =

loadIm

age(i+

1);}

return innerIm

gs; }

@Overrid

e public vo

id done() {

try { imgs =

get(); }

catch (java.u

til.concurren

t.Execu

tionExcep

tion e) { …

} }

}; �

All

concre

te subcla

sses

of SwingWorke

r implement doInBackg

round;

implementation of d

one is o

ptional

Swing & th

read

46

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�You m

ay w

onder if th

e co

de th

at se

ts imgs is u

nnecessa

rily complica

ted.

Why m

ake doInBackg

round re

turn an object a

nd use done to

retrie

ve it?

Why n

ot ju

st have doInBackg

round se

t imgs d

irectly?

�The problem is th

at th

e object im

gs re

fers to

is created in

the w

orke

r thread and used in

the event d

ispatch

thread. W

hen objects a

re sh

ared

between th

reads in

this w

ay, yo

u m

ust m

ake su

re th

at ch

anges m

ade in

one th

read are visib

le to

the other. U

sing get g

uarantees th

is, because

usin

g get cre

ates a

happens b

efore re

lationship between th

e co

de th

at

creates im

gs a

nd th

e co

de th

at u

ses it.

�There are actu

ally

two ways

to retrie

ve the object

returned by

doInBackg

round: in

voke SwingWorker.g

et with

no arguments, i.e

. if the

backg

round task

is not finish

ed get blocks

until

it is;

otherwise

, a

timeout can be specifie

d, i.e. if the tim

eout expires first,

getthrows

java.util.co

ncurre

nt.T

imeoutExce

ption.

�Be ca

reful w

hen in

vokin

g eith

er o

verlo

ad of g

et fro

m th

e event d

ispatch

thread; u

ntil g

et re

turns, n

o GUI e

vents a

re being processe

d, a

nd th

e

GUI is

"frozen".

Don't invoke get with

out arguments

unless

you are

confident th

at th

e backg

round ta

sk is complete or clo

se to

completion.

Swing & th

read

Page 24: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

47

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�It is o

ften useful fo

r a backg

round ta

sk to provid

e in

terim

results

while it

is still

workin

g. The task

can do this

by

invokin

g SwingWorker.p

ublish

method, w

hich

acce

pts a

set

of a

rguments.

�To

collect

results

provid

ed

by

publish

, overrid

e

SwingWorker.p

rocess, w

hich

will b

e in

voked fro

m th

e event

disp

atch

thread. R

esults fro

m m

ultip

le in

vocations o

f publish

are ofte

n accu

mulated fo

r a sin

gle invocation of p

rocess.

�Let's lo

ok a

t the w

ay th

e Flipperexample uses p

ublish

to

provid

e in

terim

results. T

his p

rogram generates a

series o

f random boolean values

in a backg

round task.

This

is equiva

lent to flip

ping a coin; hence the name Flipper.

To

report

its results,

the backg

round task

uses an object

of

type FlipPair

Swing & th

read

48

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

private static class Flip

Pair {

private fin

al long head

s, total; Flip

Pair(lo

ng head

s, long to

tal) { this.h

eads =

head

s; this.to

tal = total; }

} �

The heads fie

ld is th

e number o

f times th

e ra

ndom va

lue has b

eentru

e;

the to

tal fie

ld is th

e to

tal n

umber o

f random va

lues. T

he backg

round

task is re

presented by a

n insta

nce of F

lipTask:

private class Flip

Task exten

ds S

wingWorker {

@Overrid

e protected

void doInBackg

round() {

long head

s = 0; lo

ng to

tal = 0;

Random

random = new

Random();

while (!isC

ancelled

()) { total+

+;

if (random.nextB

oolean

()) { head

s++; }

publish

(new

FlipPair(h

eads, to

tal)); } retu

rn null; }

Swing & th

read

Page 25: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

49

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

protected

void process(List p

airs) { Flip

Pair p

air = pairs.g

et(pairs.size() -

1);

head

sText.setT

ext(Strin

g.fo

rmat("%

d", p

air.head

s));totalT

ext.setText(S

tring.fo

rmat("%

d", p

air.total));

�Because publish

is invoked ve

ry frequently, a

lot o

f FlipPair

values

will

probably

be accu

mulated before process

is invoked in the event disp

atch

thread; process

is only

intereste

d in

the la

st value re

porte

d each tim

e, u

sing it to

update th

e GUI

Swing & th

read

50

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�To ca

ncel a

running backg

round ta

sk, invoke SwingWorker.can

cel.The

task m

ust co

operate w

ith its o

wn ca

ncellation. T

here are tw

o w

ays it

can do th

is: �

By te

rminatin

g when it re

ceive

s an interru

pt.

�By

invokin

g SwingWorker.isC

anceled

at short

interva

ls. This

method

returns tru

e if ca

ncel has b

een invoked fo

r this S

wingWorke

r. �

The can

cel method ta

kes a

single boolean argument. If th

e argument is

true, cancel sends

the backg

round task

an interru

pt.

Whether the

argument is

true or false

, invokin

g cancel changes the cancellation

status o

f the object to

true. T

his is th

e va

lue re

turned by isC

anceled.

Once ch

anged, th

e ca

ncellation sta

tus ca

nnot b

e ch

anged back.

�The Flipper example fro

m the previo

us sectio

n uses the sta

tus-o

nly

idiom. T

he m

ain lo

op in

doInBackg

round exits w

hen isC

ancelled re

turns

true. T

his w

ill occu

r when th

e user clicks th

e "C

ancel" b

utto

n, trig

gerin

g

code th

at in

vokes ca

ncel w

ith an argument o

f false

(no interru

pt).

�The sta

tus-o

nly

approach makes

sense for

Flipper

because its

implementation of S

wingWorke

r.doInBackg

round does n

ot in

clude any

code th

at m

ight th

row In

terru

ptedExce

ption.

Swing & th

read

Page 26: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

51

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Le sw

ing si

basano su eventi

asso

ciati

alle azio

ni eseguite

dall’u

tente. Consid

eriamo un esempio di un botto

ne che, se

cliccato, d

eve fa

re emette

re un su

ono:

public class B

eeper ... im

plem

ents A

ctionListen

er {...//w

here in

itialization occu

rs: button

.addActio

nListen

er(this);

... public void

actionPerform

ed(Action

Even

t e) { ...//M

ake a beep

sound... }

} �

The Beeper cla

ss implements th

e Actio

nListe

nerinterfa

ce, w

hich

contains o

ne m

ethod: a

ctionPerfo

rmed. S

ince Beeper im

plements

Actio

nListe

ner, a

Beeper o

bject ca

n re

giste

r as a

listener fo

r the

actio

n events

that butto

ns

fire. Once the Beeper has

been

registe

red usin

g the Butto

n addActio

nListe

ner

method,

the

Beeper's a

ctionPerfo

rmed m

ethod is ca

lled every tim

e th

e butto

n

is clicked.

Swing & eventi

52

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�You ca

n te

ll what kin

ds o

f events a

component ca

n fire

by lo

okin

g

at the kinds of event listeners

you can registe

r on it.

For

example, th

e JC

omboBox cla

ss defines th

ese liste

ner re

g m

ethods:

�addActio

nListe

ner

�addIte

mListe

ner

�addPopupMenuListe

ner

�Thus,

a combo box

supports

actio

n, item, and popup menu

listeners

in additio

n to the liste

ner methods

it inherits

from

JComponent. A

component fire

s only th

ose events for w

hich

listeners have registered on it.

For example, if

an actio

n

listener is re

giste

red on a particu

lar co

mbo box, b

ut th

e co

mbo

box h

as n

o other liste

ners, th

en th

e co

mbo box w

ill fire only a

ction

events —

no ite

m or p

opup m

enu events.

�Liste

ners su

pporte

d by S

wing co

mponents fa

ll into tw

o ca

tegories:

�liste

ners th

at a

ll swing co

mponents su

pport

�other sp

ecific liste

ners th

at sw

ing co

mponents su

pport

Swing & eventi

Page 27: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

53

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Because all S

wing co

mponents d

esce

nd fro

m th

e AWT Component cla

ss, you ca

n re

giste

r the following common lis

teners on any co

mponent:

�component listener:

Listens for changes in the component's

size,

positio

n, o

r visibility.

�focus lis

tener: Liste

ns fo

r whether th

e co

mponent g

ained or lo

st the

ability to

receive

keyboard input.

�key lis

tener: Liste

ns fo

r key p

resse

s; key e

vents a

re fire

d only b

y the

component th

at h

as th

e cu

rrent ke

yboard fo

cus.

�mouse lis

tener: Liste

ns fo

r mouse clicks a

nd m

ouse m

ovement in

to or

out o

f the co

mponent's d

rawing area.

�mouse-m

otion listener:

Listens for changes in the curso

r's positio

n

over th

e co

mponent.

�mouse-wheel listener(in

troduced in 1.4):

Listens for mouse wheel

movement o

ver th

e co

mponent.

�All S

wing co

mponents d

esce

nd fro

m th

e AWT Container cla

ss, but m

any

of them aren't used as containers.

So any Swing component can fire

container events,

which

notify

listeners

that a component has been

added or removed. However,

only

containers

(such as

panels

and

frames) a

nd co

mpound co

mponents (su

ch as co

mbo boxes) typ

ically fire

container e

vents.

Swing & eventi

54

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Any number of event liste

ner objects

can liste

n for all kin

ds of

events fro

m any n

umber o

f event so

urce

objects. F

or e

xample, a

program m

ight cre

ate one liste

ner p

er e

vent so

urce

. Or a

program

might have a sin

gle liste

ner for all events

from all source

s. A

program ca

n even have m

ore th

an one liste

ner fo

r a sin

gle kin

d of

event fro

m a sin

gle event so

urce

. �

Multip

le liste

ners

can registe

r to be notifie

d of events

of a

particu

lar typ

e fro

m a particu

lar so

urce

. Also

, the sa

me liste

ner

can liste

n to

notifica

tions fro

m diffe

rent o

bjects.

�Each event is

represented by an object

that give

s inform

ation

about th

e event a

nd id

entifie

s the event so

urce

. Event so

urce

s are

ofte

n co

mponents o

r models, b

ut o

ther (a

ny…

) kinds o

f objects

can also

be event so

urce

s. �

Whenever yo

u want to

detect e

vents fro

m a particu

lar co

mponent,

first check th

e how-to

sectio

n fo

r that co

mponent. In

How to U

se Color C

hoosers , fo

r insta

nce, yo

u'll fin

d an example of w

riting a

change liste

ner to tra

ck when the color changes in the color

chooser.

Swing & eventi

Page 28: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

55

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�The most importa

nt rule to keep in mind

about event

listeners

that they

should execute very

quickly.

Because all

drawing and event-liste

ning methods are executed in the same

thread, a

slow event-liste

ner m

ethod ca

n m

ake th

e program se

em

unresponsive

and slo

w to

repaint itse

lf. If you need to

perfo

rm

some lengthy o

peration as th

e re

sult o

f an event, d

o it b

y startin

g

up another thread (or somehow sending a request

to another

thread) to

perfo

rm th

e operation.

�You have many choices on how to implement an event

listener.

We ca

n't re

commend a sp

ecific a

pproach because one

solution w

on't su

it all situ

ations. Y

ou m

ight ch

oose to

implement

separate cla

sses fo

r diffe

rent kin

ds o

f event liste

ners. T

his ca

n be

an easy a

rchitectu

re to

maintain, b

ut m

any cla

sses ca

n also

mean

reduced perfo

rmance.

�When desig

ning yo

ur p

rogram, yo

u m

ight w

ant to

implement yo

ur

event liste

ners in

a cla

ss that is n

ot p

ublic, b

ut so

mewhere m

ore

hidden.

A

priva

te

implementation

is a

more

secure

implementation.

Swing & eventi

56

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Every event-lis

tener m

ethod has a single argument—

an

object

that inherits

from the EventObject

class.

Alth

ough the

argument a

lways d

esce

nds fro

m EventObject, its typ

e is g

enerally

specifie

d m

ore precise

ly. For e

xample, th

e argument fo

r methods

that h

andle m

ouse events is a

n in

stance of M

ouseEvent, w

here

MouseEvent is a

n indire

ct subcla

ss of E

ventObject.

�The EventObject

class

defines one very

useful method Object

getSource(), th

at re

turns th

e object th

at fire

d th

e event.

�Note th

at th

e getSource

method re

turns a

n Object. E

vent cla

sses

sometim

es define methods sim

ilar to getSource

, but that have

more restricte

d return typ

es,

e.g.

getComponent

returns

a

Component o

bject. E

ach how-to

page fo

r event liste

ners m

entions

whether yo

u sh

ould use getSource

or a

nother m

ethod.

�Ofte

n, an event cla

ss defines methods that return inform

ation

about th

e event. F

or e

xample, yo

u ca

n query a

MouseEvent o

bject

for in

form

ation about w

here th

e event o

ccurre

d, h

ow m

any clicks

the user m

ade, w

hich

modifie

r keys w

ere presse

d, a

nd so

on.

Swing & eventi

Page 29: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

57

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Events ca

n be divid

ed in

to tw

o groups: lo

w-level events

and semantic events. Lo

w-le

vel events re

present w

indow-

system occu

rrences o

r low-le

vel in

put. E

veryth

ing else

is a

semantic e

vent. E

xamples o

f low-le

vel e

vents in

clude m

ouse

and key events

—both of which

result directly

from user

input. E

xamples o

f semantic e

vents in

clude actio

n and ite

m

events. A

semantic e

vent m

ight b

e trig

gered by u

ser in

put;

for e

xample, a

butto

n cu

stomarily fire

s an actio

n event w

hen

the user clicks it, a

nd a te

xt field fire

s an actio

n event w

hen

the user presse

s Enter.

However,

some semantic

events

aren't trig

gered by lo

w-le

vel e

vents, a

t all. F

or e

xample, a

table-m

odel event might be fire

d when a table model

receive

s new data fro

m a database.

Swing & eventi

58

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Whenever

possib

le, you should listen for semantic

events

rather th

an lo

w-le

vel e

vents. so

your co

de is ro

bust

and porta

ble as possib

le. For example, liste

ning for actio

n

events

on butto

ns,

rather than mouse events,

means that

the butto

n will

react

appropriately

when the user trie

s to

activa

te th

e butto

n usin

g a ke

yboard alternative

or a

look-

and-fe

el-sp

ecific g

estu

re.

�When dealing with

a compound componentsuch as a

combo box, it's im

perative

that yo

u stick to

semantic e

vents,

since yo

u have no re

liable w

ay o

f registe

ring liste

ners o

n all

the lo

ok-a

nd-fe

el-sp

ecific co

mponents th

at m

ight b

e used to

form

the co

mpound co

mponent.

Swing & eventi

Page 30: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

59

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Some liste

ner in

terfa

ces co

ntain more th

an one method. F

or e

xample,

the MouseListe

ner

interfa

ce contains

five methods:

mousePresse

d,

mouseReleased, m

ouseEntered, m

ouseExite

d, a

nd m

ouseClicke

d. E

venif

you care only

about mouse clicks,

if your cla

ss directly

implements

MouseListe

ner, th

en yo

u m

ust im

plement a

ll five MouseListe

ner m

ethods.

Methods fo

r those events yo

u don't ca

re about ca

n have empty b

odies.

//An exam

ple th

at implem

ents a listen

er interface d

irectly. public class M

yClass im

plem

ents M

ouseListen

er { ... som

eObject.ad

dMouseListen

er(this); ...

public vo

id m

ouseP

ressed(M

ouseE

vent e) { }

public vo

id m

ouseR

eleased(M

ouseE

vent e) { }

public vo

id m

ouseE

ntered

(MouseE

vent e) { }

public vo

id m

ouseE

xited(M

ouseE

vent e) { }

public vo

id m

ouseC

licked(M

ouseE

vent e) {

...//Even

t listener im

plem

entatio

n goes h

ere... } }

Swing & eventi

60

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�The re

sultin

g co

llectio

n of e

mpty m

ethod bodies ca

n m

ake co

de harder

to re

ad and m

aintain. T

o help yo

u avoid im

plementing empty m

ethod

bodies,

the API generally

inclu

des an adaptercla

ss for each liste

ner

interfa

ce w

ith m

ore th

an one m

ethod. F

or e

xample, th

e M

ouseAdapter

class

implements

the MouseListe

ner

interfa

ce.

An adapter

class

implements

empty

versio

ns of all its

interfa

ce's

methods.

To use

an

adapter, yo

u cre

ate a su

bcla

ss of it a

nd overrid

e only th

e m

ethods o

f interest,

rather than directly

implementin

g all methods of the liste

ner

interfa

ce.

/* * A

n exam

ple o

f extending an

adapter class in

stead of *

directly

implem

entin

g a listen

er interface. */

public class M

yClass exten

ds M

ouseA

dapter {

... someO

bject.ad

dMouseListen

er(this); ...

public vo

id m

ouseC

licked(M

ouseE

vent e) {

...//Even

t listener im

plem

entatio

n goes h

ere... } }

Swing & eventi

Page 31: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

61

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Generalmente,

i liste

ner

sono

realizza

ti all’in

terno

di

un’applica

zione co

me cla

sse innesta

ta (e

ventualmente anonima):

//An exam

ple of u

sing an

inner class.

public class M

yClass exten

ds A

pplet {

... someO

bject.ad

dMouseListen

er(new

MyAdapter()); ...

class MyAdapter exten

ds M

ouseA

dapter {

public void

mouseC

licked(M

ouseE

vent e) {

...//Even

t listener im

plem

entation

goes h

ere... } } } �

Tramite cla

sse anonima:

//An exam

ple of u

sing an

anonym

ous in

ner class.

public class M

yClass exten

ds A

pplet {

... someO

bject.ad

dMouseListen

er(new

MouseA

dapter() {

public void

mouseC

licked(M

ouseE

vent e) {

...//Even

t listener im

plem

entation

goes h

ere... } }); ... } }

Swing & eventi

62

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Ogni co

mponente grafico

, quando si o

pera su

di esso

, genera un evento

che descrive

cosa è

acca

duto (a

ttenzio

ne: il co

ncetto

di e

vento non si

applica

necessa

riamente solo agli oggetti

grafici,

ma ègeneralmente

con la grafica

che esso

assu

me rile

vanza e co

mprensio

ne im

mediata)

�Tipica

mente, o

gni co

mponente può generare m

olti tip

i dive

rsi di e

venti,

in re

lazio

ne a ciò

che sta

acca

dendo

�In Java, un evento è

un oggetto

, ista

nza di (una sotto

classe

di)

java.util.E

ventObject

Swing & eventi

Page 32: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

63

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Quando si

interagisce

con un componente "attivo

" si

genera un

evento, che è

un oggetto

Event della (so

tto)cla

sse opportu

na;

l’oggetto

Event contiene tutte

le inform

azio

ni sull’e

vento (ch

i l’ha

creato, co

sa è

succe

sso, e

cc); il sistema in

via ta

le oggetto

Event

all’o

ggetto

Liste

ner

(asco

ltatore degli

eventi)

preventiva

mente

registra

to, ch

e gestisce

l’evento.

�L’a

ttivitànon è

più

algoritm

ica (in

put/co

mputazio

ne/output),

èinterattiva

e re

attiva

con opportu

ne azio

ni

�Quando vie

ne ad esempio premuto un botto

ne, esso

genera un

evento di cla

sse Actio

nEvent;

questo

evento vie

ne invia

to dal

sistema allo sp

ecifico

asco

ltatore degli e

venti p

er q

uel botto

ne.

�L'a

scoltatore degli

eventi

deve implementare la interfa

ccia

Actio

nListe

ner, e

può esse

re un oggetto

di u

n'altra

classe

al d

ifuori

del pannello o può esse

re anche il p

annello ste

sso (th

is)�

Tale asco

ltatore degli

eventi

deve implementare il

metodo che

gestisce

l’evento definito nella interfa

ccia actio

nListe

ner,

in

partico

lare actio

nPerfo

rmed(Actio

nEvent e

v)

Swing & eventi

64

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Esempio: u

n'applica

zione co

stituita da un'etich

etta

(JLabel) e

un pulsa

nte

(JButto

n);

l'etich

etta

può valere "Tizio

" o "Caio“(all'in

izio vale "Tizio

“). Premendo il botto

ne, l'etich

etta

deve commutare, dive

ntando "Caio" se

era "T

izio", o

"Tizio

" se era "C

aio“:

public class E

s8Panel exten

ds JP

anel im

plem

ents A

ctionListen

er{private JLab

el l;public E

s8Panel(){

super();

l = new

JLabel("T

izio");

add(l);

JButto

n b = new

JButto

n("T

izio/Caio");

// Tizio

/Caio

èl'etich

etta del p

ulsan

teb.ad

dActio

nListen

er(this);

// registra l'o

ggetto

panel stesso

come

// ascoltato

re degli even

tiadd(b); } …

Swing & eventi

Page 33: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

65

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

…public vo

id actio

nPerfo

rmed(Actio

nEven

t e){if

(l.getT

ext().equals("T

izio"))

l.setText("C

aio");

else l.setText("T

izio");

}}import java.aw

t.*; im

port javax.sw

ing.*;

import java.aw

t.event.*

;public class E

sSwing8 {

public static vo

id m

ain(Strin

g[] v){

JFrame f =

new

JFrame(”E

sempio 7");

Contain

er c = f.g

etConten

tPane();

Es8Panel p

= new

Es8P

anel();

c.add(p);f.p

ack(); f.show(); }}

Swing & eventi

66

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Altro

esempio: C

ambiare il co

lore di sfo

ndo tra

mite due pulsa

nti: u

no lo

rende ro

ssa, l'a

ltro azzu

rro

�Arch

itettu

ra dell'a

pplica

zione: Un pannello che contiene i due pulsa

nti

creati d

al co

strutto

re del p

annello, e

d un unico

asco

ltatore degli e

venti

per e

ntra

mbi i p

ulsa

nti, q

uindi n

ecessità

di ca

pire, in

actio

nPerfo

rmed(),

quale pulsa

nte è

stato premuto

public class E

s9Panel exten

ds JP

anel im

plem

ents

Actio

nListen

er {JButto

n b1, b

2;

public E

s9Panel(){

super();

b1 = new

JButto

n("R

osso");

b2 = new

JButto

n("A

zzurro

");b1.ad

dActio

nListen

er(this);

b2.ad

dActio

nListen

er(this);

// il pannello

fa da asco

ltatore d

egli even

ti per en

trambi i p

ulsan

tiadd(b1);

add(b2);}

Swing & eventi

Page 34: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

67

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

…public vo

id actio

nPerfo

rmed(Actio

nEven

t e){Object p

ulsan

tePrem

uto = e.g

etSource();

// si recupera il riferim

ento all'o

ggetto

// che h

a generato

l'evento

if (pulsan

tePrem

uto=

=b1)

// e si confron

ta questa con

i riferimenti

// agli o

ggetti b

otto

ni b1 e b

2setB

ackground(Color.red

);if (p

ulsan

tePrem

uto=

=b2)

setBackg

round(Color.cyan

);}

}�

Un modo alternativo

per capire chi aveva generato l'evento poteva

esse

re quello di guardare l'e

tichetta

asso

ciata al pulsa

nte:

Strin

g nome =

e.getA

ctionCommand();

if nome.eq

uals("R

osso") …

Swing & eventi

68

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Le operazio

ni sulle finestre

(fin

estra

chiusa,

aperta

, minimizza

ta,

ingrandita…) g

enerano un W

indowEvent

�Gli eventi

di finestra

sono gestiti

dai metodi dich

iaratidall'in

terfa

ccia

WindowListe

ner

public vo

id windowClosed

(Window

Even

t e);public vo

id windowClosin

g(W

indow

Even

t e);public vo

id windowOpened(W

indowEven

t e);public vo

id windowIco

nified

(WindowEven

t e);public vo

id windowDeico

nified

(WindowEven

t e);public vo

id windowActivated

(WindowEven

t e);public vo

id windowDeactivated

(WindowEven

t e);�

ogni m

etodo vie

ne invocato dall'e

vento appropriato;

�Il

comporta

mento predefinito di questi

metodi va già

bene tra

nne

windowClosin

g(), ch

e non fa

uscire

l'applica

zione m

a nasco

nde so

lo la

finestra

; per far sì

che ch

iudendo la

finestra

del fra

me l'a

pplica

zione

venga ch

iusa, il fra

me deve im

plementare l'in

terfa

ccia W

indowListe

ner,

e rid

efinire W

indowClosin

g in m

odo ch

e invochi Syste

m.exit()

�Gli a

ltri metodi d

evono esse

re im

plementati, m

a, n

on dovendo svo

lgere

compiti p

recisi, p

osso

no esse

re definiti co

n un co

rpo vu

oto

Swing & eventi

Page 35: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

69

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

public class E

sSwing9 {

public static vo

id m

ain(Strin

g[] v){

JFrame f =

new

JFrame("E

sempio 9");

Contain

er c = f.g

etConten

tPane();

Es9Panel p

= new

Es9P

anel();

c.add(p);

f.addWindowListen

er( new

Term

inato

r() );// T

erminato

r èla classe ch

e implem

enta

// l'interfaccia W

indowListen

erf.p

ack();f.sh

ow();

}}class T

erminato

r implem

ents W

indowListen

er {public vo

id windowClosed

(Window

Even

t e){}public vo

id windowClosin

g(W

indow

Even

t e){System

.exit(0);// cosìch

iudendo la fin

estra si esce dalla ap

plicazio

ne

}}

Swing & eventi

70

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Il JT

extF

ield è

un co

mponente "ca

mpo di te

sto", u

sabile per scrive

re

e visu

alizza

re una rig

a di te

sto

�il ca

mpo di te

sto può esse

re editabile o no

�il te

sto è

acce

ssibile co

n getText() / se

tText()

�Il ca

mpo di te

sto è

parte

di un oggetto

Document

�Ogni volta che il testo

in esso

contenuto cambia si

genera un

DocumentEvent n

el documento ch

e co

ntiene il ca

mpo di te

sto�

Se però è

sufficie

nte re

gistra

re i ca

mbiamenti so

lo quando si p

reme

INVIO, b

asta

gestire

semplice

mente il so

lito Actio

nEvent

�ESEMPIO

�Un'applica

zione co

mprendente un pulsa

nte e due ca

mpi di te

sto�

uno per scrive

re te

sto, l'a

ltro per visu

alizza

rlo�

Quando si p

reme il p

ulsa

nte, il te

sto del se

condo ca

mpo (n

on

modifica

bile dall'u

tente) vie

ne ca

mbiato, e

reso uguale a quello

scritto nel prim

o�

L'unico

evento è

ancora il p

ulsa

nte premuto: a

ncora non usia

mo

il DocumentEvent

Swing & eventi

Page 36: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

71

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

public class E

sSwing {

public static vo

id m

ain(Strin

g[] v){

JFrame f =

new

JFrame("E

sempio");

Contain

er c = f.g

etConten

tPane();

Es10Panel p

= new

Es10Panel();

c.add(p);

f.addWindow

Listener( n

ew Term

inato

r() );f.setS

ize(300,120);

f.show();

}}

Swing & eventi

72

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Il pannello:

class Es10Panel exten

ds JP

anel im

plem

ents A

ctionListen

er {JButto

n b;

JTextField

txt1, txt2

;public E

s10Panel(){

super();

b = new

JButto

n("A

ggiorna");

txt1=new

JTextField

("Scrivere q

ui il testo

", 25);

txt2 = new

JTextField

(25); // larg

hezza in

caratt.txt2.setE

ditab

le(false); // non m

odificab

ileb.ad

dActio

nListen

er(this);

add(txt1);

add(txt2);

add(b);

} public vo

id actio

nPerfo

rmed(Actio

nEven

t e){txt2.setT

ext( txt1.getT

ext() );}}

Swing & eventi

Page 37: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

73

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

�Sfru

ttiamo il co

ncetto

di documento

che sta

dietro

a ogni ca

mpo di te

sto�

A ogni m

odifica

del co

ntenuto, il d

ocumento di cu

i il campo di te

sto fa

parte

genera un DocumentEvent p

er se

gnalare l'a

vvenuto ca

mbiamento

�Tale evento dev'e

ssere gestito

da un opportu

no D

ocumentListe

ner cio

èda

un

oggetto

di

una

classe

che

implementi

l'interfa

ccia

DocumentListe

ner

�L'interfa

ccia DocumentListener d

ichiara tre

metodi:

�void insertU

pdate(DocumentEvent e

);�void re

moveUpdate(DocumentEvent e

);�void ch

angedUpdate(DocumentEvent e

);�

Il terzo

non è

mai ch

iamato da JT

extF

ield, se

rve so

lo per a

ltri componenti

�L'o

ggetto

-evento DocumentEvent p

assa

to co

me parametro

in re

altà

esiste

solo per uniform

ità, in quanto cosa sia

acca

duto è

già

implicito

nel

metodo ch

iamato.

�Nel nostro

caso: l'a

zione da svo

lgere in ca

so di in

serim

ento o rim

ozio

ne di

caratte

ri èidentica

, quindi i due metodi insertU

pdate e removeUpdate

saranno identici,

ma vanno comunque implementati,

analogamente al

metodo ch

angedUpdate(DocumentEvent e

)

Swing & eventi

74

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

import javax.sw

ing.even

t.*;class E

s12Panel exten

ds JP

anel im

plem

ents D

ocumentListen

er {JTextField

txt1, txt2

;public E

s12Panel(){

super();

txt1= new

JTextField

("Scrivere q

ui il testo

", 25);

txt2 = new

JTextField

(25);

txt2.setEditab

le(false);txt1.g

etDocument().ad

dDocumentListen

er(this);

// ricava il documento di cu

i il campo

// di test txt1 fa p

arte e gli asso

cia il// p

annello

come listen

eradd(txt1);

add(txt2);

}Public

void insertU

pdate(D

ocumentEven

t e){txt2.setT

ext(txt1.getT

ext());}

public vo

id rem

oveU

pdate(D

ocumentEven

t e){txt2.setText(txt1.g

etText()); }

public vo

id ch

angedUpdate(D

ocumentEven

t e){}A ogni in

serim

ento o ca

ncellazio

ne di ca

ratte

ri l'aggiornamento è

automatico

Swing & eventi

Page 38: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

75

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Layout

�E’possib

ile dare una stru

ttura (la

yout) a

ll’applica

zione basata su

swing

�Esisto

no dive

rsi layout p

redefiniti in

Java, il p

rimo èBorderLayout:

�Every co

ntent p

ane is in

itialize

d to

use a BorderLa

yout. A

BorderLa

yout

places co

mponents in

up to

five areas: to

p, b

otto

m, le

ft, right,

and

center. A

ll extra

space is p

laced in

the ce

nter a

rea, e

ventually

resizin

g

its dimensio

ns, co

nsequently e

nlarging th

e entire

frame.

76

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Layout

�The BoxLayoutcla

ss puts co

mponents in

a

single row or

column.

It respects

the

components' re

queste

d m

axim

um size

s and

also

lets yo

u align co

mponents.

�The CardLayoutcla

ss lets yo

u im

plement a

n area th

at co

ntains d

ifferent

components

at diffe

rent tim

es.

A CardLayout is

ofte

n contro

lled by a

combo box, w

ith th

e sta

te of th

e co

mbo box d

eterm

ining w

hich

panel

(group of co

mponents) th

e CardLayout d

isplays. A

n alternative

tousin

g

CardLayout is u

sing a ta

bbed pane, w

hich

provid

es sim

ilar fu

nctio

nality

but w

ith a pre-defined GUI.

Page 39: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

77

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Layout

�FlowLayout is th

e default la

yout m

anager fo

r every JP

anel. It sim

ply

lays o

ut co

mponents in

a sin

gle ro

w, sta

rting a new ro

w if its co

ntainer

isn't

sufficie

ntly

wide.

Both panels

in CardLayoutDemo,

shown

previo

usly, u

se FlowLayout.

�Grid

BagLayout

is a

sophistica

ted,

flexib

le

layout

manager.

It aligns

components b

y placin

g th

em with

in a grid

of cells,

allowing some components

to

span m

ore th

an one ce

ll. The ro

ws in

the

grid

can have diffe

rent h

eights, a

nd grid

columns ca

n have diffe

rent w

idths.

78

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Layout

�Grid

Layout

simply

makes

a

bunch of components

equal in

size and disp

lays

them in the

requeste

d number of rows and

columns.

�Sprin

gLayout is

a flexib

le layout manager

desig

ned fo

r use by G

UI b

uilders. It le

ts you

specify

precise

relationships

between the

edges of components

under its

contro

l. For

example, yo

u m

ight d

efine th

at th

e le

ft edge

of o

ne co

mponent is a

certa

in dista

nce (w

hich

can be dynamica

lly calcu

lated) fro

m th

e rig

ht

edge of a

second co

mponent.

Page 40: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

79

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Layout

�A layout m

anager is a

n object th

at im

plements th

e La

youtManager

interfa

ce and determ

ines th

e size

and positio

n of th

e co

mponents

with

in a container.

Alth

ough components

can provid

e size

and

alignment h

ints, a

container's la

yout m

anager h

as th

e fin

al say

on the size and positio

n of

the components

with

in the

container.

�As a

rule, th

e only co

ntainers w

hose layout m

anagers yo

u need to

worry a

bout a

re JP

anelsand co

ntent p

anes. E

ach JP

anel o

bject is

initia

lized to

use a FlowLayout, u

nless yo

u sp

ecify d

ifferently w

hen

creatin

g th

e JP

anel. C

ontent p

anes u

se BorderLa

yout b

y default. If

you don't like

the default la

yout m

anager th

at a

panel o

r content

pane uses, yo

u're fre

e to

change it to

a diffe

rent o

ne:

�You ca

n se

t a panel's la

yout m

anager u

sing th

e JP

anel co

nstru

ctor:

JPanel p

anel =

new

JPanel(n

ew Bord

erLayout());

�In th

e se

cond ca

se,afte

r a co

ntainer h

as b

een cre

ated, yo

u ca

n se

t its la

yout m

anager u

sing th

e se

tLayout m

ethod:

Contain

er conten

tPane =

frame.g

etConten

tPane();

conten

tPane.setLayou

t(new

FlowLayou

t());

80

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Layout

�Alth

ough we re

commend th

at yo

u use layout m

anagers, yo

u ca

n perfo

rm

layout w

ithout th

em. B

y settin

g a co

ntainer's la

yout p

roperty to

null, yo

u

make th

e co

ntainer u

se no layout m

anager. W

ith th

is strategy, a

bsolute

positio

ning, yo

u m

ust sp

ecify th

e size

and positio

n of e

very co

mponent

with

in that container.

One drawback

of absolute positio

ning is

that it

doesn't a

djust w

ell w

hen th

e to

p-le

vel co

ntainer is re

sized. It a

lso doesn't

adjust w

ell to

diffe

rences b

etween users a

nd syste

ms, su

ch as d

ifferent

font size

s and locales.

�When yo

u add co

mponents to

a panel o

r content p

ane, th

e arguments

you sp

ecify to

the add m

ethod depend on th

e la

yout m

anager th

at th

e

panel o

r content p

ane is u

sing. F

or e

xample, B

orderLa

yout re

quires th

at

you specify

the area to which

the component sh

ould be added, usin

g

code like

this: p

ane.add(aComponent, B

orderLa

yout.P

AGE_START); T

he

how-to

sectio

n for each layout manager has details

on what,

if any,

arguments

you need to specify

to the add method. Some layout

managers,

such as Grid

BagLayout and Sprin

gLayout,

require elaborate

setup procedures.

Many

layout

managers,

however,

simply

place

components b

ased on th

e order th

ey w

ere added to

their co

ntainer.

Page 41: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

81

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Layout

�Sometim

es

you need to custo

mize

the size

hints

that a

component provid

es to its

container's

layout manager,

so

that th

e co

mponent w

ill be laid out w

ell. Y

ou can do th

is by

specifying one or more of the minimum, preferre

d,

and maximum sizes of th

e co

mponent. Y

ou ca

n in

voke th

e

component's

methods

for

settin

g

size

hints

—setMinimumSize

, setPreferre

dSize

, and se

tMaxim

umSize

. �

Besid

es

provid

ing size

hints,

you can also provide

alignment h

ints. F

or e

xample, yo

u ca

n sp

ecify th

at th

e to

p

edges

of

two components

should be aligned. You set

alignment

hints

eith

er

by

invokin

g the component's

setAlignmentX and se

tAlignmentY m

ethods

�Atte

nzio

ne perch

éle rich

ieste

espresse

nei due punti

precedenti so

no nella m

aggior p

arte

dei ca

si, ignorate

82

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Layout

�Three facto

rs influence the amount of space between visib

le

components in

a co

ntainer:

�The layout manager;

Some layout managers

automatica

lly put space between components;

others

don't.

Some let you

specify

the amount of space between components.

See the

how-to

page for each layout manager for inform

ation about

spacin

g su

pport.

�Invisible

components;

You

can

create

lightweight

components

that perfo

rm no paintin

g, but that can take up

space in the GUI.

Ofte

n, you use invisib

le components

in

containers co

ntro

lled by B

oxLa

yout.

�Empty borders; N

o m

atte

r what th

e layout m

anager, yo

u ca

n

affe

ct the apparent a

mount o

f space between co

mponents b

y adding empty b

orders to

components. T

he best ca

ndidates fo

r empty b

orders a

re co

mponents w

ith no default b

order, su

ch as

panels a

nd labels. S

ome other co

mponents m

ight n

ot w

ork w

ell

with

borders in

some look-a

nd-fe

el im

plementations, b

ecause of

the way th

eir p

aintin

g co

de is im

plemented.

Page 42: Java e la grafica - unict.it€¦ · Java 2D API Enables assistive technologies, such as screen read ers and Braille displays, to get information from the u ser interface. Accessibility

83

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Layout

�Layout

managers

have diffe

rent

strengths

and weaknesse

s. Flexib

le la

yout m

anagers su

ch as G

ridBagLayout a

nd Sprin

gLayout

can fu

lfill many la

yout n

eeds, h

owever th

e rig

ht la

yout d

epends o

n

the scenario

you fa

ce with

:�

You need to

disp

lay a

component in

as m

uch sp

ace as it ca

n get; If

it's the only

component in its

container,

use Grid

Layoutor

BorderLa

yout. O

therwise

, BorderLa

yout o

r Grid

BagLayoutmight b

e

a good match

. If

you use BorderLa

yout,

you'll

need to put the

space-hungry co

mponent in

the ce

nter. W

ith Grid

BagLayout, yo

u'll

need to set

the constra

ints

for

the component

so that

fill=Grid

BagConstra

ints.B

OTH.

Another

possib

ility is

to

use

BoxLa

yout, m

akin

g th

e sp

ace-hungry co

mponent sp

ecify ve

ry large

preferre

d and m

axim

um size

s. �

You need to

disp

lay a

few co

mponents in

a co

mpact ro

w at th

eir

natural size

. Consid

er u

sing a JP

anel to

group th

e co

mponents a

nd

usin

g eith

er the JPanel's

default

FlowLayoutmanager or the

BoxLa

youtmanager. S

prin

gLayoutis a

lso good fo

r this.

84

A. Longheu –Linguaggi M

-Z –Ing. In

f. 2008-2009

Layout

�If yo

u need to

disp

lay a

few co

mponents o

f the sa

me size

in ro

ws

and co

lumns, G

ridLayout is th

e rig

ht ch

oice

�If

you need to disp

lay a few components

in a row or column,

possib

ly with

varyin

g amounts

of space between them, custo

m

alignment,

or custo

m component size

s, BoxLa

yout is

the rig

ht

choice

�You need to

disp

lay a

ligned co

lumns, a

s in a fo

rm-like

interfa

ce

where a column of labels

is used to describ

e text

fields in an

adjacent column. Sprin

gLayoutis

a natural choice

for this.

The

Sprin

gUtilitie

s cla

ss used by several Tutorial examples defines a

makeCompactG

rid m

ethod th

at le

ts you easily a

lign m

ultip

le ro

ws

and co

lumns o

f components.

�You have a co

mplex la

yout w

ith m

any co

mponents. C

onsid

er e

ither

usin

g a very

flexib

le layout manager such as Grid

BagLayoutor

Sprin

gLayout,

or grouping the components

into one or more

JPanels to

simplify la

yout. If yo

u ta

ke th

e la

tter a

pproach, e

ach

JPanel m

ight u

se a diffe

rent la

yout m

anager.