ºÝºÝߣ

ºÝºÝߣShare a Scribd company logo
Programmare in Java 
Fondamenti 
Antonio Furone 
Gennaio 2000
Introduzione alla programmazione OO 
?Le classi 
?Propriet¨¤ e metodi 
?Gli oggetti 
?L¡¯ereditariet¨¤ 
?Incapsulamento 
?Overloading 
?Polimorfismo 
?Persistenza 
?Simula 
? Smalltalk 
? C++ 
? Visual Basic 
? Java
Introduzione alla programmazione OO 
UML
Caratteristiche di Java 
?Piattaforma o linguaggio di programmazione ? 
?Java Virtual Machine (JVM) 
?Web 
? Non supporta l¡¯aritmetica dei puntatori 
? Object Oriented 
? Multi-thread 
? Garbage collection 
? Sicurezza
Compilazione e Runtime 
Hello.java 
javac Hello.java 
Hello.class 
(bytecode) 
Compilazione 
Class 
Loader 
Byte code 
verifier 
Interpreter 
Runtime 
JIT code 
generator 
Hardware 
Runtime
HelloWorldApp 
public class HelloWorldApp 
{ 
public static void main (String args[]) 
{ 
System.out.println(¡°Hello World!!¡±); 
} 
}
Packages 
java.lang (String, Math, Integer, Thread,¡­) 
java.awt (Abstract Window Toolkit) 
java.applet 
java.net (Socket, URL,¡­) 
java.io 
java.util (Date, System properties)
Struttura del linguaggio 
?Commenti /*, //, /** (javadoc: descrizione dichiarazione) 
?; (fine istruzione) 
? {..} (blocco di istruzioni) 
? abstract, case, new, this, while, ¡­. (Keywords) 
? boolean, char[2], byte[1], short[2], int[4], long[8], 
float[4] ,double[8] 
(Tipi primitivi) 
?Dichiarazione variabili 
?Assegnazioni 
?Istanze 
?Allocazione della memoria 
?Scope delle variabili 
?Convenzioni di codifica
?=C/C++ 
?Logici 
!,|,&,^ 
?Concatenazione di stringhe: + 
?Shift Operators: 
128 << 1 : 256 
16 << 2 : 64 
128 >> 1 : 64 
Casting di Espressioni: 
Operatori 
long longvalue=99L; 
int intvalue=(int)longvalue; 
long longvalue=99; //int 
int intvalue=99L; 
double z=12.414F; 
float z1=12.414;
Statements 
if (boolean expression) 
{ 
statement or block; 
} 
[ 
else 
{statement or block; 
} 
] 
switch (expression) 
{ 
case const1: 
statements; 
break; 
¡­ 
default: 
statements; 
break; } 
for (init_expr; bool_expr; alter_expr) 
{ 
statement or block; 
}
Statements 
while (boolean expression) 
{ 
statement or block; 
} 
do 
{ 
statement or block; 
} while (boolean test) 
? break [label]; 
? continue [label]; 
? label: statement;
Arrays 
char s[]; 
Point p[]; 
s=new char[20]; 
p=new Point[100]; 
p[0]=new Point(); 
... 
String names[]= { 
¡°pippo¡±, 
¡°pluto¡±, 
¡°topolino¡± 
}; 
Myclass array[]= 
{ 
new Myclass(); 
new Myclass(); 
new Myclass(); 
}
Arrays 
array.length; 
int twoDim[][]=new int [4][]; 
twoDim[0]=new int[7]; 
... 
int twoDim[][]=new int[4][5]; 
...
Arrays 
int elements[]=new int[6]; 
elements=new int[10]; 
... 
int myArray[]={1,2,3,4,5,6}; 
int hold[]={10,9,8,7,6,5,4,3,2,1}; 
System.arraycopy(myArray,0,hold,0,myArray.length); 
...
Object Orientation 
?classi e oggetti 
?ereditariet¨¤ 
?metodi e costruttori 
?passaggio di parametri 
?this e super 
?polimorfismo 
?overloading e overriding 
?instanceof operator 
if (e instanceof Manager) 
{... 
} 
?package e import 
? static 
? final 
? abstract class
Object Orientation - Interfacce 
?E¡¯ come concetto molto simile a quello di classe astratta 
?Tutti i metodi di un interfaccia sono astratti 
?Le intefacce permettono di ottenere l¡¯ereditariet¨¤ multipla 
?Un interfaccia pu¨° estendere un¡¯altra interfaccia 
public interface Base 
{ 
public static final int PROP=1; 
public int mioMetodo(); 
} 
public MioApplet extends Applet 
implements Base, Runnable 
{... 
}
Object Orientation 
if (x==y) 
{ 
} 
Condizione vera se x e y referenziano lo stesso oggetto 
If (x.equals(y)) 
{ 
} 
Condizione vera se x e y sono oggetti identici. E¡¯ un metodo 
della classe Object (come toString()) che spesso viene 
riscritto.
Object Orientation - Inner Class 
public class MyFrame extends Frame 
{ 
... 
class ButtonListener implements ActionListener 
{ 
} 
... 
}
Eccezioni 
String names[]={¡°pippo¡±,¡±pluto¡±,¡±paperino¡± }; 
int i=0; 
¡­ 
while (i<4) 
{ 
try 
{System.out.println(names[i]);} 
catch (ArrayIndexOutOfBoundsException e) 
{System.out.println(¡°Verificata eccezione=¡°+ 
e.getMessage()); 
break;} 
finally 
{ 
System.out.println(¡°Sempre eseguito¡±); 
} 
}
Eccezioni
Eccezioni 
public class MyException extends Exception 
{ 
} 
¡­ 
public void mioMetodo() throws MyException 
{ 
¡­ 
throw new MyException(); 
} ¡­ 
try 
{ 
obj.mioMetodo(); 
} 
catch (MyException e) 
{ 
} 
...
AWT 
java.awt package
AWT - Frames 
import java.awt.*; 
public class MyFrame extends Frame 
{ 
public MyFrame(String str) 
{ 
super(str); 
} 
public static void main(String args[]) 
{ 
MyFrame fr=new MyFrame(¡°Hello!¡±); 
fr.setLocation(30,30); 
fr.setSize(500,500); 
//fr.setBounds(30,30,500,500); 
fr.setBackground(Color.blue); 
fr.setVisible(true); 
} 
}
AWT - Panels 
¡­ 
Panel pan=new Panel(); 
pan.setSize(100,100); 
pan.setBackground(Color.yellow); 
fr.add(pan); 
...
AWT - Layouts 
Il layout dei componenti all¡¯interno di un container ¨¨ governato 
da un Layout Manager 
? FlowLayout (default per Panel e Applet) 
? BorderLayout (default per Window, Dialog e Frame) 
? GridLayout 
? CardLayout 
? GridBagLayout
AWT - FlowLayout 
pan.setLayout(new FlowLayout()); 
Button b1=new Button(¡°One¡±); 
Button b2=new Button(¡°Two¡±); 
pan.add(b1); 
pan.add(b2); 
¡­ 
fr.pack(); 
setLayout(new FlowLayout(FlowLayout.LEFT)); 
setLayout(new FlowLayout(FlowLayout.RIGHT,20,60));
AWT- Layouts 
BorderLayout 
pan.setLayout(new BorderLayout()); 
Button b1=new Button(¡°One¡±); 
Button b2=new Button(¡°Two¡±); 
pan.add(b1,BorderLayout.NORTH); 
pan.add(b2, BorderLayout.SOUTH); 
¡­ 
GridLayout 
pan.setLayout(new GridLayout(2,1)); 
Button b1=new Button(¡°One¡±); 
Button b2=new Button(¡°Two¡±); 
pan.add(b1); 
pan.add(b2); 
¡­
AWT - CardLayout 
CardLayout mycard=new CardLayout(); 
... 
pan.setLayout(mycard); 
Panel p1=new Panel(); 
p1.add(new Label (¡°First¡±); 
Panel p2=new Panel(); 
p2.add(new Label (¡°Second¡±); 
fr.add(p1,¡±First¡±); 
fr.add(p2,¡±Second¡±); 
fr.pack(); 
¡­ 
mycard.show(fr,¡±First¡±);
Eventi 
Evento: un oggetto che descrive cosa si ¨¨ verificato 
Gli eventi possono essere uni-cast e multi-cast 
Button 
Action event 
actionPerformed (ActionEvent e) 
{ 
}
Eventi 
Listener 
import java.awt.event.*; 
public class ButtonHandler 
implements ActionListener 
{ 
public void actionPerformed 
(ActionEvent e) 
{ 
} 
} 
Source 
... 
Button b=new Button(¡°Me¡±); 
b.addActionListener 
(new ButtonHandler()); 
...
Eventi
Eventi 
Dichiarazione 
public class AccountEvent extends EventObject 
{ 
} 
public interface AccountListener extends EventListener { 
public void accountUpdate(AccountEvent e) ; 
}
Eventi 
Sorgente 
... 
private Vector listener=newVector() ; 
public void addAccountListener(AccountListener l) 
{ 
listener.addElement(l) ; 
} 
public void removeAccountListener(AccountListener l) 
{ 
listener.removeElement(l) ; 
} 
...
Eventi 
Sorgente 
... 
AccountEvent e=new AccountEvent() ; 
syncronized(this) 
{ 
l=(Vector)listeners.clone ; 
for (i=0 ;i<l.size() ;i++) 
{ 
AccountListener acc= 
(AccountListener) l.elementAt(i) ; 
acc.accountUpdate(e) ; 
} 
} 
...
Eventi 
Listener 
public class AccountAdapter implements AccountListener 
{ 
public void accountUpdate(AccountEvent e) 
{ 
} 
}
AWT Component 
Checkbox 
public class MyFrame extends Frame implements 
ItemListener 
{ 
... 
public static void main(String args[]) 
{ 
... 
fr.setLayout(new FlowLayout()); 
Checkbox one=new Checkbox("One",true); 
Checkbox two=new Checkbox("Two",false); 
one.addItemListener(fr); 
two.addItemListener(fr); 
fr.add(one); 
fr.add(two); 
fr.pack(); 
... 
}
AWT Component 
Checkbox 
public void itemStateChanged(ItemEvent e) 
{ 
String stato="deselected"; 
if (e.getStateChange()==ItemEvent.SELECTED) 
stato="selected"; 
System.out.println(stato); 
} 
... 
}
AWT Component 
Checkbox Group 
CheckboxGroup cbg=new CheckboxGroup(); 
Checkbox one=new Checkbox("One",cbg,true); 
Checkbox two=new Checkbox("Two",cbg,false); 
Choice 
Choice ch=new Choice(); 
ch.addItem("Uno"); 
ch.addItem("Due"); 
fr.add(ch); 
Si utilizza ItemListener per intercettare l¡¯item selezionato
AWT Component 
Canvas 
import java.awt.*; 
import java.awt.event.*; 
public class MyCanvas extends Canvas 
{ 
public void paint(Graphics g) 
{ 
g.setColor(Color.red); 
g.fillRect(0,0,getSize().width,getSize().height); 
} 
} 
Label 
Label lb=new Label("Hello!");
AWT Component 
TextField e TextArea 
TextField tf=new TextField("Hello!",30); 
fr.add(tf); 
Il tasto <ENTER> pu¨° essere intercettato attraverso l¡¯evento Action. 
TextArea ta=new TextArea("Hello!",4,30); 
fr.add(ta); 
Attraverso TextListener ¨¨ possibile intercettare le modifiche del 
testo visualizzato in entrambi i componenti.
AWT Component 
List 
List lst=new List(4,false); 
lst.add("Item1"); 
lst.add("Item2"); 
lst.add("Item3"); 
Il doppio click sulla lista pu¨° essere intercettato attravrso l¡¯evento 
Action. 
Dialog 
Dialog d=new Dialog(fr,"Dialog",true); 
d.add(new Button("Button")); 
d.pack(); 
¡­ 
d.setVisible(true);
AWT Component 
FileDialog 
FileDialog d=new FileDialog(fr,"FileDialog"); 
¡­ 
d.setVisible(true); 
¡­ 
String fname=d.getDirectory()+d.getFile(); 
ScrollPane 
Panel p=new Panel(); 
ScrollPane sp=new 
ScrollPane(); 
p.setLayout(new 
GridLayout(2,2)); 
p.add(new Button("Uno")); 
p.add(new Button("Due")); 
p.add(new Button("Tre")); 
p.add(new Button("Quattro"));
AWT Component 
MenuBar 
MenuBar mb=new MenuBar(); 
fr.setMenuBar(mb); 
Menu 
Menu m=new Menu("Men¨´"); 
mb.add(m); 
¡­ 
mb.setHelpMenu(mh); 
E¡¯ possibile intercettare 
l¡¯evento Action sia sull¡¯ oggetto 
Menu che su MenuItem.
MenuItem 
MenuItem it1=new MenuItem("Item1"); 
MenuItem it2=new MenuItem("Item2"); 
MenuItem it3=new MenuItem("Item3"); 
m.add(it1); 
m.add(it2); 
m.add(it3); CheckboxMenuItem 
CheckboxMenuItem cbm=new 
CheckboxMenuItem("Check Item"); 
m.add(cbm); 
E¡¯ possibile monitorare lo stato 
di un CheckboxMenuItem 
attraverso un ItemListener. 
AWT Component
Applet 
Metodi Chiave ? init() 
? start() 
? stop() 
? destroy() 
? paint() 
import java.awt.*; 
import java.applet.*; 
public class MyApplet extends Applet 
{ 
public void paint (Graphics g) 
{ 
g.drawString("Hello World!",25,25); 
} 
}
Applet 
import java.awt.*; 
import java.awt.event.*; 
import java.applet.*; 
public class MyApplet extends Applet 
{ 
Image img; 
AudioClip sound; 
public void init() 
{ 
img=getImage(getDocumentBase(),"city.gif"); 
sound=getAudioClip(getDocumentBase(),"beth1.mid"); 
} 
...
public void paint (Graphics g) 
{ 
g.drawImage(img,2,2,this); 
} 
public void start() 
{ 
//sound.play(); 
sound.loop(); 
} 
public void stop() 
{ 
sound.stop(); 
} 
} 
?Attraverso l¡¯interfaccia 
MouseListener ¨¨ possibile 
intercettare gli eventi generati 
dal mouse; 
? Con getParameter ¨¨ possibile 
leggere i parametri passati 
attraverso il tag param 
Applet
Threads 
Runnable Interface 
public class MyThread implements Runnable 
{ 
int i; 
public void run() 
{i=0; 
while (true) 
{ System.out.println("Ciao " + i); 
if (i==50) break; 
try{ 
Thread.sleep(10); 
} 
catch (InterruptedException e) {} 
i++;} 
} 
...
Threads 
Runnable Interface 
... 
public static void main (String args[]) 
{ 
for (int j=0;j<4;j++) 
{ 
MyThread mt= new MyThread (); 
Thread t=new Thread(mt); 
t.start(); 
} 
} 
}
Threads 
Metodi della classe Thread 
?isAlive() 
?sleep() 
?join() - aspetta che l¡¯esecuzione del thread sia terminata 
?wait(), notify() - classe Object 
?suspend() 
?resume() 
?stop() 
?yield() 
Il problema della sincronizzazione: 
synchronized (this) 
{ 
} 
public synchronized String pop(this) 
{ 
}
Stream I/O e Files 
Classi Base 
? FileInputStream e FileOutputStream 
? BufferedInputStream e BufferedOutputStream 
? DataInputStream e DataOutputStream 
? PipedInputStream e PipedOutputStream
Stream I/O e Files 
Serializzazione (interfaccia Serializable) e persistenza 
fos=new FileOutputStream("date.ser"); 
¡­ 
ObjectOutputStream os=new 
ObjectOutputStream(fos); 
fis=new FileInputStream("date.ser"); 
¡­ 
ObjectInputStream is=new 
ObjectInputStream(fis); 
Date dt=new Date(); 
dt=(Date)is.readObject(); 
... 
is.close(); 
fis.close(); 
Date dt=new Date(); 
... 
os.writeObject(dt); 
os.close(); 
fos.close();
Stream I/O e Files 
La parola chiave transient evita la serializzazione di alcune 
propriet¨¤ della classe 
public transient Thread myT;
Stream I/O e Files 
Scrivere un file 
... 
PrintWriter out= new PrintWriter(new 
BufferedWriter(new FileWriter("foo.out"))); 
out.println("riga"); 
out.close(); 
... 
Leggere un file 
BufferedReader in 
= new BufferedReader(new FileReader("foo.out")); 
System.out.println(in.readLine()); 
in.close(); 
...
TCP/IP Socket 
Host 
Server 
Client 
Host/Port 
Port 
TCP/IP
TCP/IP Socket 
Server 
public static void main (String args[]) 
{ 
ServerSocket s=null; 
Socket s1; 
OutputStream os; 
DataOutputStream dos; 
try 
{ 
s=new ServerSocket(9800); 
} 
catch (IOException e) 
{} 
while (true) 
{ 
try 
{ 
s1=s.accept(); 
os=s1.getOutputStream(); 
dos=new DataOutputStream(os); 
dos.writeUTF("Ciao!!!"); 
dos.close(); 
os.close(); 
s1.close(); 
} 
catch (IOException e) 
{} 
} 
} 
}
TCP/IP Socket 
public static void main (String args[]) 
throws IOException 
{ 
Socket s1; 
InputStream is; 
DataInputStream dis; 
s1=new Socket("1101-7521",9800); 
is=s1.getInputStream(); 
dis=new DataInputStream(is); 
String st=new String(dis.readUTF()); 
System.out.println(st); 
dis.close(); 
is.close(); 
s1.close(); 
} 
Client
JFC - Swing 
? Architettura Model/View/Controller 
? Look and Feel 
JButton 
ItemSelectable 
ButtonModel 
DefaultButtonModel 
Altri modelli 
Delegate(View/Controller) Model 
ComponentUI 
ButtonUI 
BasicButtonUI 
MacButtonUI 
MotifButtonUI
JFC - Swing
JFC - Swing 
import javax.swing.*; 
import java.awt.*; 
public class MyFrame extends JFrame 
{ 
public MyFrame(String str) 
{ 
super(str); 
} 
public static void main(String args[]) 
{ 
try 
{ 
UIManager.setLookAndFeel 
("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); 
} 
catch(Exception e) 
{System.out.println(e.getMessage());}
JFC - Swing 
MyFrame fr=new MyFrame("Hello!"); 
fr.setLocation(30,30); 
fr.setSize(400,400); 
fr.getContentPane().setLayout(new FlowLayout()); 
fr.getContentPane().add(new JButton("Ciao!")); 
JComboBox cb=new JComboBox(); 
DefaultComboBoxModel mcb=new DefaultComboBoxModel(); 
mcb.addElement("Item 1"); 
mcb.addElement("Item 2"); 
cb.setModel(mcb); 
fr.getContentPane().add(cb); 
fr.pack(); 
fr.setVisible(true); 
} 
}
Printing 
... 
PrinterJob printJob = PrinterJob.getPrinterJob(); 
printJob.printDialog(); 
printJob.setPrintable(this); 
try { printJob.print(); } catch (Exception PrintException) { } 
...
Printing 
Implementando l¡¯interfaccia Printable: 
... 
public int print(Graphics g, PageFormat pf, int pi) throws 
PrinterException { 
if (pi >= 1) { 
return Printable.NO_SUCH_PAGE; 
} 
Graphics2D g2 = (Graphics2D) g; 
g2.translate(pf.getImageableX(), pf.getImageableY()); 
g2.drawString("Ciao",10,10); 
g2.setColor(Color.black); 
paint(g2); 
return Printable.PAGE_EXISTS; 
} 
...

More Related Content

Java

  • 1. Programmare in Java Fondamenti Antonio Furone Gennaio 2000
  • 2. Introduzione alla programmazione OO ?Le classi ?Propriet¨¤ e metodi ?Gli oggetti ?L¡¯ereditariet¨¤ ?Incapsulamento ?Overloading ?Polimorfismo ?Persistenza ?Simula ? Smalltalk ? C++ ? Visual Basic ? Java
  • 4. Caratteristiche di Java ?Piattaforma o linguaggio di programmazione ? ?Java Virtual Machine (JVM) ?Web ? Non supporta l¡¯aritmetica dei puntatori ? Object Oriented ? Multi-thread ? Garbage collection ? Sicurezza
  • 5. Compilazione e Runtime Hello.java javac Hello.java Hello.class (bytecode) Compilazione Class Loader Byte code verifier Interpreter Runtime JIT code generator Hardware Runtime
  • 6. HelloWorldApp public class HelloWorldApp { public static void main (String args[]) { System.out.println(¡°Hello World!!¡±); } }
  • 7. Packages java.lang (String, Math, Integer, Thread,¡­) java.awt (Abstract Window Toolkit) java.applet java.net (Socket, URL,¡­) java.io java.util (Date, System properties)
  • 8. Struttura del linguaggio ?Commenti /*, //, /** (javadoc: descrizione dichiarazione) ?; (fine istruzione) ? {..} (blocco di istruzioni) ? abstract, case, new, this, while, ¡­. (Keywords) ? boolean, char[2], byte[1], short[2], int[4], long[8], float[4] ,double[8] (Tipi primitivi) ?Dichiarazione variabili ?Assegnazioni ?Istanze ?Allocazione della memoria ?Scope delle variabili ?Convenzioni di codifica
  • 9. ?=C/C++ ?Logici !,|,&,^ ?Concatenazione di stringhe: + ?Shift Operators: 128 << 1 : 256 16 << 2 : 64 128 >> 1 : 64 Casting di Espressioni: Operatori long longvalue=99L; int intvalue=(int)longvalue; long longvalue=99; //int int intvalue=99L; double z=12.414F; float z1=12.414;
  • 10. Statements if (boolean expression) { statement or block; } [ else {statement or block; } ] switch (expression) { case const1: statements; break; ¡­ default: statements; break; } for (init_expr; bool_expr; alter_expr) { statement or block; }
  • 11. Statements while (boolean expression) { statement or block; } do { statement or block; } while (boolean test) ? break [label]; ? continue [label]; ? label: statement;
  • 12. Arrays char s[]; Point p[]; s=new char[20]; p=new Point[100]; p[0]=new Point(); ... String names[]= { ¡°pippo¡±, ¡°pluto¡±, ¡°topolino¡± }; Myclass array[]= { new Myclass(); new Myclass(); new Myclass(); }
  • 13. Arrays array.length; int twoDim[][]=new int [4][]; twoDim[0]=new int[7]; ... int twoDim[][]=new int[4][5]; ...
  • 14. Arrays int elements[]=new int[6]; elements=new int[10]; ... int myArray[]={1,2,3,4,5,6}; int hold[]={10,9,8,7,6,5,4,3,2,1}; System.arraycopy(myArray,0,hold,0,myArray.length); ...
  • 15. Object Orientation ?classi e oggetti ?ereditariet¨¤ ?metodi e costruttori ?passaggio di parametri ?this e super ?polimorfismo ?overloading e overriding ?instanceof operator if (e instanceof Manager) {... } ?package e import ? static ? final ? abstract class
  • 16. Object Orientation - Interfacce ?E¡¯ come concetto molto simile a quello di classe astratta ?Tutti i metodi di un interfaccia sono astratti ?Le intefacce permettono di ottenere l¡¯ereditariet¨¤ multipla ?Un interfaccia pu¨° estendere un¡¯altra interfaccia public interface Base { public static final int PROP=1; public int mioMetodo(); } public MioApplet extends Applet implements Base, Runnable {... }
  • 17. Object Orientation if (x==y) { } Condizione vera se x e y referenziano lo stesso oggetto If (x.equals(y)) { } Condizione vera se x e y sono oggetti identici. E¡¯ un metodo della classe Object (come toString()) che spesso viene riscritto.
  • 18. Object Orientation - Inner Class public class MyFrame extends Frame { ... class ButtonListener implements ActionListener { } ... }
  • 19. Eccezioni String names[]={¡°pippo¡±,¡±pluto¡±,¡±paperino¡± }; int i=0; ¡­ while (i<4) { try {System.out.println(names[i]);} catch (ArrayIndexOutOfBoundsException e) {System.out.println(¡°Verificata eccezione=¡°+ e.getMessage()); break;} finally { System.out.println(¡°Sempre eseguito¡±); } }
  • 21. Eccezioni public class MyException extends Exception { } ¡­ public void mioMetodo() throws MyException { ¡­ throw new MyException(); } ¡­ try { obj.mioMetodo(); } catch (MyException e) { } ...
  • 23. AWT - Frames import java.awt.*; public class MyFrame extends Frame { public MyFrame(String str) { super(str); } public static void main(String args[]) { MyFrame fr=new MyFrame(¡°Hello!¡±); fr.setLocation(30,30); fr.setSize(500,500); //fr.setBounds(30,30,500,500); fr.setBackground(Color.blue); fr.setVisible(true); } }
  • 24. AWT - Panels ¡­ Panel pan=new Panel(); pan.setSize(100,100); pan.setBackground(Color.yellow); fr.add(pan); ...
  • 25. AWT - Layouts Il layout dei componenti all¡¯interno di un container ¨¨ governato da un Layout Manager ? FlowLayout (default per Panel e Applet) ? BorderLayout (default per Window, Dialog e Frame) ? GridLayout ? CardLayout ? GridBagLayout
  • 26. AWT - FlowLayout pan.setLayout(new FlowLayout()); Button b1=new Button(¡°One¡±); Button b2=new Button(¡°Two¡±); pan.add(b1); pan.add(b2); ¡­ fr.pack(); setLayout(new FlowLayout(FlowLayout.LEFT)); setLayout(new FlowLayout(FlowLayout.RIGHT,20,60));
  • 27. AWT- Layouts BorderLayout pan.setLayout(new BorderLayout()); Button b1=new Button(¡°One¡±); Button b2=new Button(¡°Two¡±); pan.add(b1,BorderLayout.NORTH); pan.add(b2, BorderLayout.SOUTH); ¡­ GridLayout pan.setLayout(new GridLayout(2,1)); Button b1=new Button(¡°One¡±); Button b2=new Button(¡°Two¡±); pan.add(b1); pan.add(b2); ¡­
  • 28. AWT - CardLayout CardLayout mycard=new CardLayout(); ... pan.setLayout(mycard); Panel p1=new Panel(); p1.add(new Label (¡°First¡±); Panel p2=new Panel(); p2.add(new Label (¡°Second¡±); fr.add(p1,¡±First¡±); fr.add(p2,¡±Second¡±); fr.pack(); ¡­ mycard.show(fr,¡±First¡±);
  • 29. Eventi Evento: un oggetto che descrive cosa si ¨¨ verificato Gli eventi possono essere uni-cast e multi-cast Button Action event actionPerformed (ActionEvent e) { }
  • 30. Eventi Listener import java.awt.event.*; public class ButtonHandler implements ActionListener { public void actionPerformed (ActionEvent e) { } } Source ... Button b=new Button(¡°Me¡±); b.addActionListener (new ButtonHandler()); ...
  • 32. Eventi Dichiarazione public class AccountEvent extends EventObject { } public interface AccountListener extends EventListener { public void accountUpdate(AccountEvent e) ; }
  • 33. Eventi Sorgente ... private Vector listener=newVector() ; public void addAccountListener(AccountListener l) { listener.addElement(l) ; } public void removeAccountListener(AccountListener l) { listener.removeElement(l) ; } ...
  • 34. Eventi Sorgente ... AccountEvent e=new AccountEvent() ; syncronized(this) { l=(Vector)listeners.clone ; for (i=0 ;i<l.size() ;i++) { AccountListener acc= (AccountListener) l.elementAt(i) ; acc.accountUpdate(e) ; } } ...
  • 35. Eventi Listener public class AccountAdapter implements AccountListener { public void accountUpdate(AccountEvent e) { } }
  • 36. AWT Component Checkbox public class MyFrame extends Frame implements ItemListener { ... public static void main(String args[]) { ... fr.setLayout(new FlowLayout()); Checkbox one=new Checkbox("One",true); Checkbox two=new Checkbox("Two",false); one.addItemListener(fr); two.addItemListener(fr); fr.add(one); fr.add(two); fr.pack(); ... }
  • 37. AWT Component Checkbox public void itemStateChanged(ItemEvent e) { String stato="deselected"; if (e.getStateChange()==ItemEvent.SELECTED) stato="selected"; System.out.println(stato); } ... }
  • 38. AWT Component Checkbox Group CheckboxGroup cbg=new CheckboxGroup(); Checkbox one=new Checkbox("One",cbg,true); Checkbox two=new Checkbox("Two",cbg,false); Choice Choice ch=new Choice(); ch.addItem("Uno"); ch.addItem("Due"); fr.add(ch); Si utilizza ItemListener per intercettare l¡¯item selezionato
  • 39. AWT Component Canvas import java.awt.*; import java.awt.event.*; public class MyCanvas extends Canvas { public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(0,0,getSize().width,getSize().height); } } Label Label lb=new Label("Hello!");
  • 40. AWT Component TextField e TextArea TextField tf=new TextField("Hello!",30); fr.add(tf); Il tasto <ENTER> pu¨° essere intercettato attraverso l¡¯evento Action. TextArea ta=new TextArea("Hello!",4,30); fr.add(ta); Attraverso TextListener ¨¨ possibile intercettare le modifiche del testo visualizzato in entrambi i componenti.
  • 41. AWT Component List List lst=new List(4,false); lst.add("Item1"); lst.add("Item2"); lst.add("Item3"); Il doppio click sulla lista pu¨° essere intercettato attravrso l¡¯evento Action. Dialog Dialog d=new Dialog(fr,"Dialog",true); d.add(new Button("Button")); d.pack(); ¡­ d.setVisible(true);
  • 42. AWT Component FileDialog FileDialog d=new FileDialog(fr,"FileDialog"); ¡­ d.setVisible(true); ¡­ String fname=d.getDirectory()+d.getFile(); ScrollPane Panel p=new Panel(); ScrollPane sp=new ScrollPane(); p.setLayout(new GridLayout(2,2)); p.add(new Button("Uno")); p.add(new Button("Due")); p.add(new Button("Tre")); p.add(new Button("Quattro"));
  • 43. AWT Component MenuBar MenuBar mb=new MenuBar(); fr.setMenuBar(mb); Menu Menu m=new Menu("Men¨´"); mb.add(m); ¡­ mb.setHelpMenu(mh); E¡¯ possibile intercettare l¡¯evento Action sia sull¡¯ oggetto Menu che su MenuItem.
  • 44. MenuItem MenuItem it1=new MenuItem("Item1"); MenuItem it2=new MenuItem("Item2"); MenuItem it3=new MenuItem("Item3"); m.add(it1); m.add(it2); m.add(it3); CheckboxMenuItem CheckboxMenuItem cbm=new CheckboxMenuItem("Check Item"); m.add(cbm); E¡¯ possibile monitorare lo stato di un CheckboxMenuItem attraverso un ItemListener. AWT Component
  • 45. Applet Metodi Chiave ? init() ? start() ? stop() ? destroy() ? paint() import java.awt.*; import java.applet.*; public class MyApplet extends Applet { public void paint (Graphics g) { g.drawString("Hello World!",25,25); } }
  • 46. Applet import java.awt.*; import java.awt.event.*; import java.applet.*; public class MyApplet extends Applet { Image img; AudioClip sound; public void init() { img=getImage(getDocumentBase(),"city.gif"); sound=getAudioClip(getDocumentBase(),"beth1.mid"); } ...
  • 47. public void paint (Graphics g) { g.drawImage(img,2,2,this); } public void start() { //sound.play(); sound.loop(); } public void stop() { sound.stop(); } } ?Attraverso l¡¯interfaccia MouseListener ¨¨ possibile intercettare gli eventi generati dal mouse; ? Con getParameter ¨¨ possibile leggere i parametri passati attraverso il tag param Applet
  • 48. Threads Runnable Interface public class MyThread implements Runnable { int i; public void run() {i=0; while (true) { System.out.println("Ciao " + i); if (i==50) break; try{ Thread.sleep(10); } catch (InterruptedException e) {} i++;} } ...
  • 49. Threads Runnable Interface ... public static void main (String args[]) { for (int j=0;j<4;j++) { MyThread mt= new MyThread (); Thread t=new Thread(mt); t.start(); } } }
  • 50. Threads Metodi della classe Thread ?isAlive() ?sleep() ?join() - aspetta che l¡¯esecuzione del thread sia terminata ?wait(), notify() - classe Object ?suspend() ?resume() ?stop() ?yield() Il problema della sincronizzazione: synchronized (this) { } public synchronized String pop(this) { }
  • 51. Stream I/O e Files Classi Base ? FileInputStream e FileOutputStream ? BufferedInputStream e BufferedOutputStream ? DataInputStream e DataOutputStream ? PipedInputStream e PipedOutputStream
  • 52. Stream I/O e Files Serializzazione (interfaccia Serializable) e persistenza fos=new FileOutputStream("date.ser"); ¡­ ObjectOutputStream os=new ObjectOutputStream(fos); fis=new FileInputStream("date.ser"); ¡­ ObjectInputStream is=new ObjectInputStream(fis); Date dt=new Date(); dt=(Date)is.readObject(); ... is.close(); fis.close(); Date dt=new Date(); ... os.writeObject(dt); os.close(); fos.close();
  • 53. Stream I/O e Files La parola chiave transient evita la serializzazione di alcune propriet¨¤ della classe public transient Thread myT;
  • 54. Stream I/O e Files Scrivere un file ... PrintWriter out= new PrintWriter(new BufferedWriter(new FileWriter("foo.out"))); out.println("riga"); out.close(); ... Leggere un file BufferedReader in = new BufferedReader(new FileReader("foo.out")); System.out.println(in.readLine()); in.close(); ...
  • 55. TCP/IP Socket Host Server Client Host/Port Port TCP/IP
  • 56. TCP/IP Socket Server public static void main (String args[]) { ServerSocket s=null; Socket s1; OutputStream os; DataOutputStream dos; try { s=new ServerSocket(9800); } catch (IOException e) {} while (true) { try { s1=s.accept(); os=s1.getOutputStream(); dos=new DataOutputStream(os); dos.writeUTF("Ciao!!!"); dos.close(); os.close(); s1.close(); } catch (IOException e) {} } } }
  • 57. TCP/IP Socket public static void main (String args[]) throws IOException { Socket s1; InputStream is; DataInputStream dis; s1=new Socket("1101-7521",9800); is=s1.getInputStream(); dis=new DataInputStream(is); String st=new String(dis.readUTF()); System.out.println(st); dis.close(); is.close(); s1.close(); } Client
  • 58. JFC - Swing ? Architettura Model/View/Controller ? Look and Feel JButton ItemSelectable ButtonModel DefaultButtonModel Altri modelli Delegate(View/Controller) Model ComponentUI ButtonUI BasicButtonUI MacButtonUI MotifButtonUI
  • 60. JFC - Swing import javax.swing.*; import java.awt.*; public class MyFrame extends JFrame { public MyFrame(String str) { super(str); } public static void main(String args[]) { try { UIManager.setLookAndFeel ("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); } catch(Exception e) {System.out.println(e.getMessage());}
  • 61. JFC - Swing MyFrame fr=new MyFrame("Hello!"); fr.setLocation(30,30); fr.setSize(400,400); fr.getContentPane().setLayout(new FlowLayout()); fr.getContentPane().add(new JButton("Ciao!")); JComboBox cb=new JComboBox(); DefaultComboBoxModel mcb=new DefaultComboBoxModel(); mcb.addElement("Item 1"); mcb.addElement("Item 2"); cb.setModel(mcb); fr.getContentPane().add(cb); fr.pack(); fr.setVisible(true); } }
  • 62. Printing ... PrinterJob printJob = PrinterJob.getPrinterJob(); printJob.printDialog(); printJob.setPrintable(this); try { printJob.print(); } catch (Exception PrintException) { } ...
  • 63. Printing Implementando l¡¯interfaccia Printable: ... public int print(Graphics g, PageFormat pf, int pi) throws PrinterException { if (pi >= 1) { return Printable.NO_SUCH_PAGE; } Graphics2D g2 = (Graphics2D) g; g2.translate(pf.getImageableX(), pf.getImageableY()); g2.drawString("Ciao",10,10); g2.setColor(Color.black); paint(g2); return Printable.PAGE_EXISTS; } ...