file MyApplication.java
import java.awt.*; public class MyApplication { public static void main (String[] args) { Frame f = new Frame(); f.setLayout (new FlowLayout()); f.setLocation(100,100); f.add (new Button("This is button 1")); f.add (new Button("This is button 2")); f.add (new TextField("This is a textfield")); f.pack(); f.show(); } }
import java.awt.*;
frame
che posizionamo al pixel(100,100) dello schermo.
FlowLayout
Container
) che possono contenere uno o piu' degli oggetti precedenti: Panel, Frame,etc
file MyApplication.java
import java.awt.*; public class MyApplication { public static void main (String[] args) { Frame f = new Frame(); f.setLayout (new GridLayout(2,2, 20, 20)); f.setLocation(100,100); f.add (new Button("This is button 1")); f.add (new Button("This is button 2")); f.add (new TextField("This is a textfield")); f.pack(); f.show(); } }
GridLayout
(disposizione a griglia) con 2 righe e 2 colonne e spaziature di 20 pixel orizontali e 20 verticali.
file MyApplication.java
import java.awt.*; public class MyApplication { public static void main (String[] args) { Frame f = new Frame(); f.setLayout (new BorderLayout()); f.setLocation(100,100); f.add ("North", new Button("North")); f.add ("West", new Button("West")); f.add ("South", new Button("South")); f.add ("Center", new Button("Center")); f.pack(); f.show(); } }
BorderLayout
come oggetto di posizionamento
della finestra.
file MyApplication.java
import java.awt.*; public class MyApplication { public static void main (String[] args) { Panel p = new Panel(new GridLayout(2,2)); p.add (new TextField("1")); p.add (new TextField("2")); p.add (new TextField("3")); Frame f = new Frame(); f.setLayout (new BorderLayout()); f.setResizable(false); f.setLocation(100,100); f.add ("North", new Button("North")); f.add ("West", new Button("Center")); f.add ("South", new Button("South")); f.add ("Center", p); f.pack(); f.show(); } }
Panel
che a sua volta e' un contenitore che contiene altri oggetti grafici posizionati usando un GridLayout.
file MyApplication.java
import java.awt.*; public class MyApplication { public static void main (String[] args) { Choice l = new Choice(); l.addItem("Item 1"); l.addItem("Item 2"); l.addItem("Item 3"); TextArea ta = new TextArea(5,20); TextField tf = new TextField(); Label lb = new Label("This is an example"); Frame f = new Frame("Some sample"); f.setLayout(new GridLayout(2,2)); f.setLocation(100,100); f.add (lb); f.add (l); f.add (tf); f.add (ta); f.pack(); f.show(); } }I metodi da usare per i vari oggetti variano da oggetto a oggetto e vanno cercati come al solito nella documentazione standard del package AWT.
Passiamo ora agli eventi che permettono alla nostra interfaccia di diventare
interattiva collegando ad esempio al click di un tasto l'esecuzione di un metodo.
Infatti una volta creato il vostro quadro di comando avete bisogno di
specificare cosa succede quando schiacciate un bottone,muovete un cursore,etc
In effetti a ogni possibile intervento dell'utente e' associato un evento con un nome particolare generato dall'oggetto grafico
corrispondente. Perche' quando si schiaccia un bottone succeda qualche cosa
dobbiamo:
file MyApplication.java
import java.awt.*; public class MyApplication { public static void main (String[] args) { Button b = new Button ("Press me"); MyActionListener alistener = new MyActionListener(); b.addActionListener(alistener); Frame f = new Frame("Some sample"); f.setLayout(new FlowLayout()); f.setLocation(100,100); f.add (b); f.pack(); f.show(); } }
file MyActionListener.java
import java.awt.event.*; public class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("A button has been pressed"); } }
java.awt.event.*
che contiene gli eventi che seguono
il modello introdotto con la versione 1.1 di Java(il modello precedente e' deprecato).
MyActionListener
che implementa l'interfaccia.
Si instanzia quindi un oggetto di questa classe chiamato alistener
e lo si registra.
file MyApplication.java
import java.awt.*; public class MyApplication { public static void main (String[] args) { List l = new List(); l.addItem("Select here"); l.addItem("...or here"); l.addItem("...or even here"); MyItemListener alistener = new MyItemListener(); l.addItemListener(alistener); Frame f = new Frame("Some sample"); f.setLayout(new FlowLayout()); f.setLocation(100,100); f.add (l); f.pack(); f.show(); } }
file MyItemListener.java
import java.awt.event.*; public class MyItemListener implements ItemListener { public void itemStateChanged(ItemEvent e) { System.out.println("An Item has been (de)selected"); } }
MyItemListener
che implementa l'interfaccia.
Si instanzia quindi un oggetto di questa classe chiamato alistener
e lo si registra.
file MyApplication.java
import java.awt.*; public class MyApplication { public static void main (String[] args) { List l = new List(); l.addItem("Select here"); l.addItem("... or here"); l.addItem("... or even here"); MyItemListener alistener = new MyItemListener(); l.addItemListener(alistener); Frame f = new Frame("Some sample"); f.setLayout(new FlowLayout()); f.setLocation(100,100); f.add (l); f.pack(); f.show(); } }
file MyItemListener.java
import java.awt.event.*; import java.awt.*; public class MyItemListener implements ItemListener { public void itemStateChanged(ItemEvent e) { Integer item = (Integer)(e.getItem()); System.out.println( "Item "+item.intValue()+" has been (de)selected"); System.out.println(); List l = (List)(e.getItemSelectable()); System.out.println ("Selected Item has text "+l.getItem(item.intValue())); } }
ItemEvent
viene passato al metodo che deve gestire l'evento.Questi oggetti hanno dei metodi appropriati che
permettono di ottenere altre informazioni relative all'evento.
getItem
permette di sapere quale elemento e' stato selezionato.
import java.awt.*; import java.applet.*; import java.awt.event.*; public class Disegna extends Applet implements MouseMotionListener,ActionListener{ int x, y; int rosso, verde,blu; Button tasto; boolean pulisci = false; public void init() { x = 10; y = 100; addMouseMotionListener(this); rosso = 0; verde=0; blu=0; add(tasto = new Button("Pulisci")); tasto.addActionListener(this); } public void mouseMoved(MouseEvent e){ x = e.getX(); y = e.getY(); rosso =(int)( Math.random()*256); verde =(int)( Math.random()*256); blu =(int)( Math.random()*256); repaint(); } public void mouseDragged(MouseEvent e){} public void actionPerformed(ActionEvent e){ pulisci = true; repaint(); } public void update(Graphics g){ paint(g); } public void paint( Graphics g) { //System.out.println("rosso,verde,blu= " +rosso+" "+verde+" "+blu); if(pulisci){ g.setColor(Color.white); g.fillRect(0,0,getSize().width,getSize().height); pulisci=false; }else{ g.setColor(new Color(rosso,verde,blu)); g.fillRect(x,y,10,10); } } }Guardate l'applet in funzione.
Container
ed ha
come LayoutManager predefinito il FlowLayout
:percio' l'istruzione add(oggetto_grafico)
permette di aggiungere
un nuovo oggetto grafico all'applet.
implements
con una lista delle opportune interfacce.
this
mouseMoved,mouseDragged e actionPerformed
MouseMotionListener
.
getX(),getY()
dell'evento MouseEvent
permettono di conoscere la posizione del cursore del mouse.
file MyApplication.java
import java.awt.*; public class MyApplication { public static void main (String[] args) { Button b = new Button ("Press me"); MyActionListener alistener = new MyActionListener(); MyMouseListener mlistener = new MyMouseListener(); b.addActionListener(alistener); b.addMouseListener(mlistener); Frame f = new Frame("Some sample"); f.setLayout(new FlowLayout()); f.setLocation(100,100); f.add (b); f.pack(); f.show(); } }
file MyActionListener.java
import java.awt.event.*; public class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("A button has been pressed"); } }
file MyMouseListener.java
import java.awt.event.*; public class MyMouseListener extends MouseAdapter { public void mouseEntered(MouseEvent e) { System.out.println("Mouse has entered this object"); } }
MouseListener
e ridefinire i suoi cinque metodi, estendiamo la classe MouseAdapter
che ha gia' delle definizioni dummy dei 5 metodi e ridefiniamo solo
il metodo MouseEntered che ci interessa.
file MyApplication.java
import java.awt.*; public class MyApplication { public static void main (String[] args) { OKButton b1 = new OKButton (); OKButton b2 = new OKButton(new MyActionListener()); Frame f = new Frame("Some sample"); f.setLayout(new FlowLayout()); f.setLocation(100,100); f.add (b1); f.add (b2); f.pack(); f.show(); } }
file MyActionListener.java
import java.awt.event.*; public class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("A button has been pressed"); } }
file OKButton.java
import java.awt.*; import java.awt.event.*; public class OKButton extends Button { // A constructor which automatically provides the text public OKButton() { super("OK"); } // A constructor to register the action listener // at instantiation time public OKButton(ActionListener al) { this(); addActionListener(al); } }
import java.awt.*; public class MyApplication { public static void main (String[] args) { Frame f = new Frame(); f.setLayout (new FlowLayout()); f.setLocation(100,100); f.add (new Button("This is button 1")); f.add (new Button("This is button 2")); f.add (new TextField("This is a textfield")); f.pack(); f.show(); } }diventa
import java.awt.*; import java.applet.*; public class Daframe1 extends Applet { public void init(){ setLayout (new FlowLayout()); add (new Button("This is button 1")); add (new Button("This is button 2")); add (new TextField("This is a textfield")); } }Guardate l'applet in funzione.
add
e setLayout
valgono identiche per l'applet.
pack,show e setLocation
non sono piu' necessari.
import java.awt.*; import java.awt.event.*; public class MyApplication { public static void main (String[] args) { Button b = new Button ("Press me"); MyActionListener alistener = new MyActionListener(); b.addActionListener(alistener); Frame f = new Frame("Some sample"); f.setLayout(new FlowLayout()); f.setLocation(100,100); f.add (b); f.pack(); f.show(); } } public class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("A button has been pressed"); } }diventa
import java.awt.*; import java.applet.*; import java.awt.event.*; public class Daframe2 extends Applet { public void init(){ Button b = new Button ("Press me"); MyActionListener alistener = new MyActionListener(); b.addActionListener(alistener); setLayout(new FlowLayout()); add (b); } } class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("A button has been pressed"); } }Guardate l'applet in funzione.
import java.awt.*; import java.applet.*; import java.awt.event.*; public class Daframe3 extends Applet { public void init(){ Button b = new Button ("Press me"); MyActionListener alistener = new MyActionListener(); b.addActionListener(alistener); setLayout(null); add (b); b.reshape(0,0,100,100); } } }Guardate l'applet in funzione.
FlowLayout
:
con l'istruzione setLayout(null)
ne impediamo l'uso.
reshape
di Button posiziona il tasto in maniera
assoluta nella finestra dell'applet dandogli le dimensioni volute.
import java.awt.*; import java.applet.*; import java.awt.event.*; public class Daframe4 extends Applet { public void init(){ Button b = new Button ("Press me"); b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ System.out.println("A button has been pressed"); } }); setLayout(new FlowLayout()); add (b); } }Guardate l'applet in funzione.
MyActionListener
possiamo definire a volo questa classe quando si registra l'oggetto listener.
addActionListener(new ActionListener(){ public void actionPerformed(actionEvent e){ trattamento evento}})
import java.awt.*; public class MyApplication { public static void main (String[] args) { Frame f = new Frame(); f.setLayout (new GridLayout(2,2, 20, 20)); f.setLocation(100,100); f.add (new Button("This is button 1")); f.add (new Button("This is button 2")); f.add (new TextField("This is a textfield")); f.pack(); f.show(); } }diventa
import java.awt.*; import java.applet.*; public class Daframe5 extends Applet { public void init(){ Frame f = new Frame(); f.setLayout (new GridLayout(2,2, 20, 20)); f.setLocation(100,100); f.add (new Button("This is button 1")); f.add (new Button("This is button 2")); f.add (new TextField("This is a textfield")); f.pack(); f.show(); } }Guardate l'applet in funzione.
frame
puo' essere usato in un'applet per creare finestre esterne al browser di dimensioni qualsiasi
e con un proprio set di menu'.
import java.awt.*; import java.applet.*; import java.awt.event.*; public class Pick1 extends Applet implements ActionListener{ int maxcol = 158; Color col[]=new Color[maxcol]; PickCanvas disegno; Button b1; Panel p1,p2; TextField c1val,c2val; Label l1,l2; double c1,c2; public void init(){ c1 = Math.random()-5.; c2 = Math.random()-5.; Julia1.setcol(col); disegno = new PickCanvas(this); p1 = new Panel(); p1.add(l1 = new Label("c1")); p1.add(c1val=new TextField(5)); c1val.setText(Double.toString(c1)); p1.add(l2 = new Label("c2")); p1.add(c2val=new TextField(5)); c2val.setText(Double.toString(c2)); p2 = new Panel(); p2.add(b1 = new Button("Disegna")); b1.addActionListener(this); setLayout(new BorderLayout()); add("North",p1); add("Center",disegno); add("South",p2); disegno.repaint(); } public void actionPerformed(ActionEvent e){ c1 = Double.valueOf(c1val.getText()).doubleValue(); if(c1<-5.)c1=-5.; if(c1 > -.4)c1=-4.; c2 = Double.valueOf(c2val.getText()).doubleValue(); if(c2<-5.)c2=-5.; if(c2 > -.4)c2=-4.; disegno.repaint(); } class PickCanvas extends Canvas{ Pick1 appl; PickCanvas(Pick1 appl1){ super(); appl=appl1; } public void paint(Graphics g){ int i,j,ncol; for(i=0;i< getSize().width;i++){ for(j=0;j< getSize().height;j++){ ncol = (int)(appl.c1*(Math.sin(-11.+appl.c2*i)+Math.sin(-12.+appl.c2*j))); ncol = Math.abs(ncol)%appl.maxcol+1; g.setColor(appl.col[ncol]); g.fillRect(i,j,1,1); } } } } }Guardate l'applet in funzione.
disegno.repaint()
actionPerformed
cio' che deve succedere quando si preme il tasto.
N.B. Con Java 2 la "Canvas" e' stata sostituita dalla classe JPanel che fa da sfondo al JApplet. In Java2 non e' piu' possibile disegnare direttamente nell'applet!
file Disegnap.java
import java.awt.*; import java.applet.*; import java.awt.event.*; public class Disegnap extends Frame{ public static void main(String [] args){ Disegnap h= new Disegnap(); Disegnah DApplet = new Disegnah(); DApplet.init(); h.add("Center", DApplet); h.pack(); h.show(); } Disegnap() { setTitle("Disegna"); } } class Disegnah extends Applet implements MouseMotionListener,ActionListener{ int x, y; int rosso, verde,blu; Button tasto; boolean pulisci = false; public Dimension getPreferredSize(){ return (new Dimension(400,400)); } public void init() { x = 10; y = 100; addMouseMotionListener(this); rosso = 0; verde=0; blu=0; add(tasto = new Button("Pulisci")); tasto.addActionListener(this); } public void mouseDragged(MouseEvent e){ x = e.getX(); y = e.getY(); rosso =(int)( Math.random()*256); verde =(int)( Math.random()*256); blu =(int)( Math.random()*256); repaint(); } public void mouseMoved(MouseEvent e){} public void actionPerformed(ActionEvent e){ pulisci = true; repaint(); } public void update(Graphics g){ paint(g); } public void paint( Graphics g) { //System.out.println("rosso,verde,blu= " +rosso+" "+verde+" "+blu); if(pulisci){ g.setColor(Color.white); g.fillRect(0,0,getSize().width,getSize().height); pulisci=false; }else{ g.setColor(new Color(rosso,verde,blu)); g.fillRect(x,y,10,10); } } }
Frame
contiene anche il metodo main
.
init
ed eventualmente start
e stop
dell'applet devono essere chiamati nel main.
getPreferredSize
che ritorna la dimensione dell'applet.