upcast - downcast - unitrentolatemar.science.unitn.it/segue_userfiles/2019... · errore! exception...

45
Upcast - downcast

Upload: others

Post on 03-Oct-2020

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Upcast-downcast

Page 2: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Conversioniforzatetratipiriferimento:castingÈpossibileforzarelaconversionedauntiporiferimentoTadunsottotipoT1purché… •  … il tipo dinamico dell’oggetto

convertito sia un sottotipo di T1

Object o = new AutomobileElettrica(); Automobile a = o; // errato, Object non è un // sottotipo di Automobile Automobile a = (Automobile) o; // corretto (casting)

Questaconversioneimplicitaconsentitadalpolimorfismo(is-a)vienechiamataupcast

Questaconversioneesplicitavienechiamatadowncast

Page 3: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

public class Test { public static void main(String a[]) { new Test(); } cast Test() { A a; B b = new B(); a=b; a.f1(); a.f2(); } }

OK:upcastimplicito

class A { void f1() {System.out.println("f1");} } class B extends A { void f2() {System.out.println("f2");} } class C extends B { void f3() {System.out.println("f3");} }

NO:"methodf2notfoundinclassA"(compiletimeerror)

Page 4: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

public class Test { public static void main(String a[]) { new Test(); } cast Test() { A a; B b = new B(); a=b; a.f1(); ((B)a).f2();

} }

class A { void f1() {System.out.println("f1");} } class B extends A { void f2() {System.out.println("f2");} } class C extends B { void f3() {System.out.println("f3");} }

OK:upcastimplicito

OK:downcastcorretto

Page 5: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

public class Test { public static void main(String a[]) { new Test(); } cast Test() { A a; B b = new B(); a=b; a.f1(); ((C)a).f3(); } } class A { void f1()

{System.out.println("f1");} } class B extends A { void f2() {System.out.println("f2");} } class C extends B { void f3() {System.out.println("f3");} }

OK:upcastimplicito

NO:downcastillecito(runtimeerror)java.lang.ClassCastException

Page 6: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Ricapitoliamolevicendedelbinding…

Page 7: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Decisionialvolo…public static void main(String a[]){ ArrayDati p; // leggi k if (k==1) p = new Pila(); else p = new Coda(); p.inserisci(1); p.inserisci(2); p.estrai(); }

Iltipodipvienedecisoaruntime!Illegametraunoggettoeilsuotipoèdinamico(dynamicbinding,latebinding,olazyevaluation)

ArrayDati

Pila Coda

Page 8: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Domanda:perchénonfarecosì?public static void main(String a[]){ //ArrayDati p; // leggi k if (k==1) Pila p = new Pila(); else Coda p = new Coda(); p.inserisci(1); p.inserisci(2); p.estrai(); }

ArrayDati

Pila Coda

Page 9: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

•  Èpossibiledeterminareiltipodinamicodiunoggettoconl’operatoreinstanceof

•  Utile per evitare errori di tipo a runtime dovuti a downcast

Determinazionedeltipo:instanceof

Point

NamedPoint

• public static void main(String a[]){ •  Point p; •  // leggi k •  if (k==1) p = new Point(2,2); •  else p = new NamedPoint(3,3,”A”); •  p.getName(); •  if (p instanceof NamedPoint) ((NamedPoint) p).getName(); • }

Page 10: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Riassuntosoluzione1:casisemplicissimi.

Aa=newA();Aab=newB();Bb=newB();a.g(a);=>A.g(A)=>A.g(A)b.g(a);=>B.g(A)=>B.g(A)b.g(b);=>B.g(B)=>B.g(B)

classA{publicvoidg(Ax){System.out.println("calledoninstanceofA");}}classBextendsA{publicvoidg(Ax){System.out.println("called1oninstanceofB");}publicvoidg(Bx){System.out.println("called2oninstanceofB");}}

calledoninstanceofAcalled1oninstanceofBcalled2oninstanceofB

Risoluzionefirmabanale,Tipostaticoetipodinamicocoincidono,nessunproblema!

Page 11: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Riassuntosoluzione2:casisemplici.

Aa=newA();Aab=newB();Bb=newB();a.g(ab);=>A.g(A)=>A.g(A)b.g(ab);=>B.g(A)=>B.g(A)

classA{publicvoidg(Ax){System.out.println("calledoninstanceofA");}}classBextendsA{publicvoidg(Ax){System.out.println("called1oninstanceofB");}publicvoidg(Bx){System.out.println("called2oninstanceofB");}}

calledoninstanceofAcalled1oninstanceofB

Risoluzionefirmabanale,Nell’argomentotipostaticoeruntimenoncoincidonomailfattononèrilevante,Tipostaticoetipodinamicocoincidono,nessunproblema!

Page 12: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Riassuntosoluzione3:dynamicbinding.

Aa=newA();Aab=newB();Bb=newB();ab.g(ab);=>A.g(A)=>B.g(A)ab.g(b);=>A.g(A)=>B.g(A)

classA{publicvoidg(Ax){System.out.println("calledoninstanceofA");}}classBextendsA{publicvoidg(Ax){System.out.println("called1oninstanceofB");}publicvoidg(Bx){System.out.println("called2oninstanceofB");}}

called1oninstanceofBcalled1oninstanceofB

Risoluzionefirmabanale,TipostaticoetipodinamicoNONcoincidono,dynamicbinding!

Page 13: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Riassuntosoluzione4:Liskov

Aa=newA();Aab=newB();Bb=newB();a.g(b);=>A.g(B)=>A.g(A)=>A.g(A)

classA{publicvoidg(Ax){System.out.println("calledoninstanceofA");}}classBextendsA{publicvoidg(Ax){System.out.println("called1oninstanceofB");}publicvoidg(Bx){System.out.println("called2oninstanceofB");}}

calledoninstanceofA

Nellarisoluzionestaticanontrovoilmetodocercato,edevoricorrereaLiskovPoinelbindingdinamicononhocomplicazioni..

Page 14: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Riassuntosoluzione5:Liskov+DynamicBinding.

Aa=newA();Aab=newB();Bb=newB();ab.g(b);=>A.g(B)=>A.g(A)=>B.g(A)

classA{publicvoidg(Ax){System.out.println("calledoninstanceofA");}}classBextendsA{publicvoidg(Ax){System.out.println("called1oninstanceofB");}publicvoidg(Bx){System.out.println("called2oninstanceofB");}}

called1oninstanceofB

Nellarisoluzionestaticanontrovoilmetodocercato,edevoricorrereaLiskovPoinelbindingdinamicodevoadattarelasoluzionetrovataall’overriding.

Page 15: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

UserInput

Page 16: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Userinput– senzagraficaimportjava.util.Scanner;...Scannerscanner=newScanner(System.in);System.out.println(”dimmiqualcosa");StringinputString=scanner.nextLine();...System.out.println(inputString);

Page 17: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Userinput–congraficaAlert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Alert Title"); alert.setHeaderText("Alert header:"); alert.setContentText("Alert Text"); alert.showAndWait();

Page 18: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Userinput–congraficaTextInputDialog dialog = new TextInputDialog("Default answer");

dialog.setTitle("Dialog Title"); dialog.setHeaderText("Dialog header"); dialog.setContentText("Answer label:"); String s= dialog.showAndWait().get();

Nonèproprioilmodogiustoperfarlo,maperora…

Page 19: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Conversionedistringheinnumeri

Page 20: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Conversionedistringheinnumeri

Strings="10";inti=Integer.parseInt(s);Stringpi="3.1415026535";floatπ=Float.parseFloat(pi);ChesuccedesefaccioStrings=”pippo";inti=Integer.parseInt(s);

?

Page 21: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Errore!ExceptioninApplicationstartmethodjava.lang.reflect.InvocationTargetException

atsun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethod)atsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)atsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)atjava.lang.reflect.Method.invoke(Method.java:498)atcom.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)atcom.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)atsun.reflect.NativeMethodAccessorImpl.invoke0(NativeMethod)atsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)atsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)atjava.lang.reflect.Method.invoke(Method.java:498)atsun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)

Causedby:java.lang.RuntimeException:ExceptioninApplicationstartmethodatcom.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)atcom.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)atjava.lang.Thread.run(Thread.java:745)

Causedby:java.lang.NumberFormatException:Forinputstring:"z"atsun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)atsun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)atjava.lang.Float.parseFloat(Float.java:451)atjavafxapplication27.JavaFXApplication27.start(JavaFXApplication27.java:36)atcom.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)atcom.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)atcom.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)atjava.security.AccessController.doPrivileged(NativeMethod)atcom.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)atcom.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)

Exceptionrunningapplicationjavafxapplication27.JavaFXApplication27

Page 22: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Gestionedeglierrori

Page 23: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Proteggiamoquestocodice

Scannerscanner=newScanner(System.in);StringinputString;intz;System.out.println("dammiunnumero");inputString=scanner.nextLine();z=Integer.parseInt(inputString);System.out.println("inputvalido!");

Page 24: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Bloccotry-catchScannerscanner=newScanner(System.in);StringinputString;intz;System.out.println("dammiunnumero");inputString=scanner.nextLine();try{

intz=Integer.parseInt(inputString);System.out.println("inputvalido!");}catch(NumberFormatExceptionex){System.out.println("inputnonvalido!");}

Page 25: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

PossiamofaredimeglioScannerscanner=newScanner(System.in);StringinputString;intz;booleanfailure=true;do{try{System.out.println("dammiunnumero");inputString=scanner.nextLine();intz=Integer.parseInt(inputString);failure=false;}catch(NumberFormatExceptionex){

failure=true;}}while(failure);

Page 26: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

ClausolafinallyNota:c’èunaulterioreclausola!try{codicechepotrebbegenerareerrore}catch(NumberFormatExceptionex){

codicedaeseguiresesiverificaunerrore}finally{codicedaeseguiresiachecisiastatounerrore,siachenoncisiastato.}

Page 27: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

finally

Thefinallyblockalwaysexecuteswhenthetryblockexits.Thisensuresthatthefinallyblockisexecutedevenifanunexpectedexceptionoccurs.Butfinallyisusefulformorethanjustexceptionhandling—itallowstheprogrammertoavoidhavingcleanupcodeaccidentallybypassedbyareturn,continue,orbreak.Puttingcleanupcodeinafinallyblockisalwaysagoodpractice,evenwhennoexceptionsareanticipated.

Page 28: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Esercizio

Page 29: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

EserciziopercasaModificareilcodicechedisegnaundisco,inmodochedopoaverdisegnatolafinestraconilcerchio(dopolastage.show()),all’utentevengachiestotramiteunDialogilvaloredelraggio,esimodifichiilcerchiousandoilvaloredato.Sigestiscanoerrori,esipongaunlimiteminimoemassimoaivaloriaccettatiperilraggio.

Page 30: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

PalestradiJavaconlagrafica:JavaFX-parte2

Page 31: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

ParenthierarchyParent•  Group•  Region•  WebView•  Control

– superclassedivariwidget,tracuiFileChooser

ARegionisanareaofthescreenthatcancontainothernodes

WebViewisaNodethatmanagesaWebEngineanddisplaysitscontent(it’sawebbrowser!).

AGroupisacontainerofothernodeswithoutanyspecifiedscreenarea

Page 32: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Shape&Text

unnodochevisualizzatesto;supportaacapo(wrapping)eparagrafiseparatida'\n'

Page 33: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

GerarchiadiShapeLeseguenticlassiimplementanoShape •  Line •  Polyline •  Polygon •  Rectangle •  Arc •  Circle •  Ellipse •  QuadCurve •  CubicCurve •  Text •  SVGPath (lineacompostadisottoelementi)

Page 34: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Nodehierarchy

Node•  Parent•  Shape•  Canvas

Page 35: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Canvas

Una"teladelpittore"conunmetodoperottenereilsuoGraphicContextconvarieprimitiveperdisegnarcisopra:- fillArc() - fillRect() - drawImage() -  …http://docs.oracle.com/javafx/2/canvas/jfxpub-canvas.htm

Page 36: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

GerarchiadiNode

Node•  Parent•  Shape•  Canvas•  ImageView•  MediaView

Page 37: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

MediaView&Media

Rappresental’entità

multimediale

Controlloredella

riproduzione

Componentegraficadella

GUI

Page 38: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

MediaViewpublic class Sounds extends Application{ public void start(Stage stage) {

Media media = new Media("http://www.ferraraterraeacqua.it/it/audioguide/audioguide-di-ferrara-citta-del-rinascimento/01_benvenuto-a-ferrara.mp3"); MediaPlayer mediaPlayer = new MediaPlayer(media); mediaPlayer.setAutoPlay(true); // create mediaView and add media player to the viewer MediaView mediaView = new MediaView(mediaPlayer); Group root = new Group(mediaView); root.getChildren().add(

new Text(10, 30,"Benvenuto a Ferrara")); Scene scene = new Scene(root, 150, 60); stage.setScene(scene);

stage.sizeToScene(); stage.show(); } public static void main(String[] args) { Application.launch(args); } }

http://docs.oracle.com/javafx/2/media/overview.htm https://docs.oracle.com/javase/8/javafx/media-tutorial/overview.htm

Page 39: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

ImageView&Image

Page 40: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

GerarchiadiParent(parziale)Parent•  Control

– superclassedivariwidget,tracuiFileChooser

•  …

Page 41: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Image&File

public class FilesAndImages extends Application { public void start(Stage stage) {

FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Carica un'immagine");

fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("JPG", "*.jpg"), new FileChooser.ExtensionFilter("PNG", "*.png") ); String url = System.getProperty("user.home"); File f=new File(url);

fileChooser.setInitialDirectory(f); // bugged on MacOsXFile file = fileChooser.showOpenDialog(stage);

if (file == null) { System.out.println("No file chosen"); System.exit(1); }

Page 42: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Image&FileImage image = new Image("file://" +

file.getAbsolutePath(), 500, 500, true, true); ImageView iw = new ImageView(image); Group root = new Group(iw); Scene scene = new Scene(root, 500,500); stage.setTitle(file.getName()); stage.setScene(scene); stage.sizeToScene(); stage.show(); }

public static void main(String[] args) { Application.launch(args); }}

Page 43: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Esempio:Finestremultiple

Page 44: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Finestremultiple:primafinestra public class Finestre extends Application { public void start(Stage stage) {

Text t=new Text(50, 100, "The quick brown fox jumps over the lazy dog");

t.setTextAlignment(TextAlignment.RIGHT); t.setWrappingWidth(50); t.setFill(Paint.valueOf("GREEN")); Group g = new Group(t); Scene scene = new Scene(g); stage.setTitle("Titolo della finestra 1"); stage.setScene(scene); // set stage dimension stage.setWidth(399);

stage.setHeight(399); // set stage position

stage.setX(1000); stage.setY(800); // make stage visible stage.show();

Page 45: Upcast - downcast - UniTrentolatemar.science.unitn.it/segue_userFiles/2019... · Errore! Exception in Application start method java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native

Finestremultiple:secondafinestra Text t2=new Text(0, 20, "Ping !\nPongPing !"); t2.setTextAlignment(TextAlignment.LEFT); t2.setFill(Paint.valueOf("RED")); t2.setFont(new Font(20));

Group g2 = new Group(t2); Scene scene2 = new Scene(g2); scene2.setFill(Paint.valueOf("YELLOW")); Stage stage2 = new Stage(); stage2.setTitle("Titolo della finestra 2"); stage2.setScene(scene2);

stage2.sizeToScene(); stage2.setX(100); stage2.setY(80); stage2.show();

} public static void main(String[] args) { launch(args); } }