Minule bolo…
description
Transcript of Minule bolo…
Minule bolo…Applety• java.awt.*;• button, text, label, combo-box, ….• events,• layouts,…
Applety Obmedzenia• applet nemôže pristupovať na lokálny disk• applet nemá menu• dialog box je mätúci
Pamätajme• applet sa naťahuje vždy znova do browsera• kvôli bezpečnosti, obmedzený prístup k lokálnym zdrojom• applet a aplikácia majú odlišné riadenie
Výhody• nepotrebuje inštaláciu … len runtime, pluggin, etc. • applet vám nezničí systém• idea nezávislej platformy
Spracovanie udalosti• action (Event evt, Object what)
stlačenie buttonu, check-box, vybratie položky z combo-boxu, ...
• keyDown (Event evt, int key)stlačenie klávesu, key predstavuje kód klávesu z evt.key
• keyUp(Event evt, int key)
uvoľnenie klávesu
• lostFocus(Event evt, Object what)strata fokusu objeku
• gotFocus(Event evt, Object what)získanie fokusu
• mouseDown(Event evt, int x, int y)stlačenie myši na súradniciach x,y
• mouseUp(Event evt, int x, int y)pustenie myši na súradniciach x,y
• mouseMove(Event evt, int x, int y)presun myši
• mouseDrag(Event evt, int x, int y)
dragovanie myši, od mouseDown po mouseUp
• mouseEnter(Event evt, int x, int y)myš vliezla do komponentu
• mouseExit(Event evt, int x, int y)myš ušla z komponentu
public boolean handleEvent(Event evt)
Spracovanie udalostíimport java.awt.*;import java.applet.*;import java.util.*;
public class AutoEvent extends Applet { Hashtable h = new Hashtable(); String[] event = { "keyDown", "keyUp", "lostFocus", "gotFocus", "mouseDown", "mouseUp", "mouseMove", "mouseDrag", "mouseEnter", "mouseExit“ }; MyButton b1 = new MyButton(this, Color.blue, "test1"),
b2 = new MyButton(this, Color.red, "test2");
public void init() { setLayout(new GridLayout(event.length+1,2)); for(int i = 0; i < event.length; i++) { add(new Label(event[i], Label.CENTER)); TextField t = new TextField(); t.setEditable(false); add(t); h.put(event[i], t); } add(b1); add(b2); }}
MyButtonimport java.awt.*;import java.applet.*;import java.util.*;
class MyButton extends Canvas { AutoEvent parent; Color color; String label;
MyButton(AutoEvent parent, Color color, String label) { this.label = label; this.parent = parent; this.color = color; }
public boolean keyDown(Event evt, int key) { TextField t = (TextField)parent.h.get("keyDown"); t.setText(evt.toString()); return true; }
public boolean keyUp(Event evt, int key) { TextField t = (TextField)parent.h.get("keyUp"); t.setText(evt.toString()); return true; }. . . . . . . . . . . . . .
public void paint(Graphics g) { g.setColor(color); int rnd = 30; g.fillRoundRect(0, 0,
size().width, size().height, rnd, rnd);
g.setColor(Color.black); g.drawRoundRect(0, 0,
size().width, size().height, rnd, rnd);
FontMetrics fm = g.getFontMetrics(); int width = fm.stringWidth(label); int height = fm.getHeight(); int ascent = fm.getAscent(); int leading = fm.getLeading(); int horizMargin = (size().width - width)/2; int verMargin = (size().height - height)/2; g.setColor(Color.white); g.drawString(label, horizMargin, verMargin + ascent + leading); }
Oknové aplikácieimport java.awt.*;
public class ToeTest extends Frame { TextField rows = new TextField("3"); TextField cols = new TextField("3");
public ToeTest() { setTitle("Toe Test"); Panel p = new Panel(); p.setLayout(new GridLayout(2,2)); p.add(new Label("Rows", Label.CENTER)); p.add(rows); p.add(new Label("Columns", Label.CENTER)); p.add(cols); add("North", p); add("South", new Button("go")); }public static void main(String[] args) { Frame f = new ToeTest(); f.resize(200,100); f.show(); }}
public boolean handleEvent(Event evt) { if(evt.id == Event.WINDOW_DESTROY) System.exit(0); else return super.handleEvent(evt); return true; }
public boolean action(Event evt, Object arg){ if (arg.equals("go")) { Dialog d = new ToeDialog(this, Integer.parseInt(rows.getText()), Integer.parseInt(cols.getText())); d.show(); } else return super.action(evt, arg); return true; }
Dialogclass ToeDialog extends Dialog { public static final int BLANK = 0; public static final int XX = 1; public static final int OO = 2; public int turn = XX;
public ToeDialog(Frame parent, int w, int h) { super(parent, "The game itself", false); setLayout(new GridLayout(w, h)); for(int i = 0; i < w * h; i++) add(new ToeButton(this)); resize(w * 50, h * 50); } public boolean handleEvent(Event evt) { if(evt.id == Event.WINDOW_DESTROY) dispose(); else return super.handleEvent(evt); return true; }}
Canvasclass ToeButton extends Canvas {
int state = ToeDialog.BLANK;
ToeDialog parent;
ToeButton(ToeDialog parent) {
this.parent = parent;
}
public void paint(Graphics g) {
int x2 = size().width - 1;
int y2 = size().height - 1;
g.drawRect(0, 0, x2, y2);
int x1 = x2/4; int y1 = y2/4;
int wide = x2/2; int high = y2/2;
if(state == ToeDialog.XX) {
g.drawLine(x1, y1, x1 + wide, y1 + high);
g.drawLine(x1, y1 + high, x1 + wide, y1);
}
if(state == ToeDialog.OO)
g.drawOval(x1, y1, x1+wide/2, y1+high/2);
}
public boolean mouseDown(Event evt, int x, int y) {
if (state == ToeDialog.BLANK) {
state = parent.turn;
parent.turn= (parent.turn == ToeDialog.XX ?
ToeDialog.OO : ToeDialog.XX);
} else
state = (state == ToeDialog.XX ?
ToeDialog.OO : ToeDialog.XX);
repaint();
return true;
}
}
Menuimport java.awt.*;
import java.lang.*;
import java.applet.*;
public class FrameMenuCrusroApplet extends Applet {
public void init() {
new FrameMenuCursor("Menu Based Cursors");
}
}
class FrameMenuCursor extends Frame {
public FrameMenuCursor(String title) {
super(title);
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
Menu m = new Menu("File");
mbar.add(m);
m.add(new MenuItem("Quit"));
m = new Menu("Cursor");
mbar.add(m);
m.add(new MenuItem("Default"));
m.add(new MenuItem("Wait"));
m.add(new MenuItem("Hand"));
m.add(new MenuItem("Move"));
. . . . . .
resize(300,200);
show();
}
Table 3.2. Event helper methods.
public boolean handleEvent(Event e) {
if (e.id == e.WINDOW_DESTROY) {
dispose(); // Erase frame
return true;
} else if (e.id == e.ACTION_EVENT) {
if (e.target instanceof MenuItem) {
String menuName = e.arg.toString();
if (menuName.equals("Quit"))
dispose();
if (menuName.equals("Default"))
setCursor(Frame.DEFAULT_CURSOR);
if (menuName.equals("Wait"))
setCursor(Frame.WAIT_CURSOR);
if (menuName.equals("Hand"))
setCursor(Frame.HAND_CURSOR);
if (menuName.equals("Move"))
setCursor(Frame.MOVE_CURSOR);
. . . . . . .
return true;
}
return true;
} else {
return false;
}
}
}
Listener modelimport java.awt.*;import java.awt.event.*; import java.applet.*;
public class Button2 extends Applet { Button b1 = new Button("Button 1"), b2 = new Button("Button 2");
public void init() { b1.addActionListener(new B1()); b2.addActionListener(new B2()); add(b1); add(b2); } class B1 implements ActionListener { public void actionPerformed(ActionEvent e) { getAppletContext().showStatus("Button 1"); } } class B2 implements ActionListener { public void actionPerformed(ActionEvent e) { getAppletContext().showStatus("Button 2"); } }}
Udalosti (eventy)Komponent Udalosť
Adjustable AdjustmentEventApplet ContainerEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEventButton ActionEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEventCanvas FocusEvent, KeyEvent, MouseEvent, ComponentEventCheckbox ItemEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEventCheckboxMenuItem ActionEvent, ItemEventChoice ItemEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEventComponent FocusEvent, KeyEvent, MouseEvent, ComponentEventContainer ContainerEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEventDialog ContainerEvent, WindowEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEventFileDialog ContainerEvent, WindowEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEventFrame ContainerEvent, WindowEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEventLabel FocusEvent, KeyEvent, MouseEvent, ComponentEventList ActionEvent, FocusEvent, KeyEvent, MouseEvent, ItemEvent, ComponentEventMenu ActionEventMenuItem ActionEventPanel ContainerEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEventPopupMenu ActionEventScrollbar AdjustmentEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEventScrollPane ContainerEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEventTextArea TextEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEventTextComponent TextEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEventTextField ActionEvent, TextEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEventWindow ContainerEvent, WindowEvent, FocusEvent, KeyEvent, MouseEvent, ComponentEvent
ListenersListener interface w/ adapter
Methods in interface
ActionListener actionPerformed(ActionEvent)
AdjustmentListener adjustmentValueChanged( AdjustmentEvent)
ComponentListener ComponentAdapter
componentHidden(ComponentEvent) componentShown(ComponentEvent) componentMoved(ComponentEvent) componentResized(ComponentEvent)
ContainerListener ContainerAdapter
componentAdded(ContainerEvent) componentRemoved(ContainerEvent)
FocusListener FocusAdapter
focusGained(FocusEvent) focusLost(FocusEvent)
KeyListener KeyAdapter
keyPressed(KeyEvent) keyReleased(KeyEvent) keyTyped(KeyEvent)
MouseListener MouseAdapter
mouseClicked(MouseEvent) mouseEntered(MouseEvent) mouseExited(MouseEvent) mousePressed(MouseEvent) mouseReleased(MouseEvent)
MouseMotionListener MouseMotionAdapter
mouseDragged(MouseEvent) mouseMoved(MouseEvent)
WindowListener WindowAdapter
windowOpened(WindowEvent) windowClosing(WindowEvent) windowClosed(WindowEvent) windowActivated(WindowEvent) windowDeactivated(WindowEvent) windowIconified(WindowEvent) windowDeiconified(WindowEvent)
ItemListener itemStateChanged(ItemEvent)
TextListener textValueChanged(TextEvent)
Check boximport java.awt.*;import java.awt.event.*;import java.applet.*;
public class RadioCheckNew extends Applet { TextField t = new TextField(30); Checkbox[] cb = { new Checkbox("Check Box 1"), new Checkbox("Check Box 2"), new Checkbox("Check Box 3") }; CheckboxGroup g = new CheckboxGroup(); Checkbox cb4 = new Checkbox("four", g, false), cb5 = new Checkbox("five", g, true), cb6 = new Checkbox("six", g, false);
public void init() { t.setEditable(false); add(t); ILCheck il = new ILCheck(); for(int i = 0; i < cb.length; i++) { cb[i].addItemListener(il); add(cb[i]); } cb4.addItemListener(new IL4()); cb5.addItemListener(new IL5()); cb6.addItemListener(new IL6()); add(cb4); add(cb5); add(cb6); }
class ILCheck implements ItemListener { public void itemStateChanged(ItemEvent e) { for(int i = 0; i < cb.length; i++) { if(e.getSource().equals(cb[i])) { t.setText("Check box " + (i + 1)); return; } } } } class IL4 implements ItemListener { public void itemStateChanged(ItemEvent e) { t.setText("Radio button four"); } } class IL5 implements ItemListener { public void itemStateChanged(ItemEvent e) { t.setText("Radio button five"); } }
Myšpublic class Mouse extends Applet implements MouseMotionListener {
int width, height; Vector listOfPositions;
public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); listOfPositions = new Vector(); addMouseMotionListener( this ); } public void mouseMoved( MouseEvent e ) { if ( listOfPositions.size() >= 50 ) listOfPositions.removeElementAt( 0 ); listOfPositions.addElement( new Point( e.getX(), e.getY() ) ); repaint(); }
public void mouseDragged( MouseEvent e ) { }
public void paint( Graphics g ) { g.setColor( Color.white ); for ( int j = 1; j < listOfPositions.size(); ++j ) { Point A = Point)(listOfPositions.elementAt(j-1)); Point B = (Point)(listOfPositions.elementAt(j)); g.drawLine( A.x, A.y, B.x, B.y ); } }}
Štýlimport java.awt.*;import import java.util.*;java.awt.event.*;
public class GoodIdea extends Frame { Button b1 = new Button("Button 1"), b2 = new Button("Button 2");
public GoodIdea() { setLayout(new FlowLayout()); b1.addActionListener(new B1L()); b2.addActionListener(new B2L()); add(b1); add(b2); } public class B1L implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button 1 pressed"); } } public class B2L implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button 2 pressed"); } }
public static void main(String[] args) { Frame f = new GoodIdea(); f.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e){ System.out.println("Window Closing"); System.exit(0); } }); f.setSize(300,200); f.setVisible(true); }}
ne-Štýlimport java.awt.*;import java.awt.event.*;import java.util.*;
public class BadIdea1 extends Frame implements ActionListener, WindowListener {
Button b1 = new Button("Button 1"), b2 = new Button("Button 2"); public BadIdea1() { setLayout(new FlowLayout()); addWindowListener(this); b1.addActionListener(this); b2.addActionListener(this); add(b1); add(b2); } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if(source == b1) System.out.println("Button 1 pressed"); else if(source == b2) System.out.println("Button 2 pressed"); else System.out.println("Something else"); }
public void windowClosing(WindowEvent e) { System.out.println("Window Closing"); System.exit(0); } public void windowClosed(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowOpened(WindowEvent e) {}
public static void main(String[] args) { Frame f = new BadIdea1(); f.setSize(300,200); f.setVisible(true); }}
Štýl-miximport java.awt.*;import java.awt.event.*;import java.util.*;
public class BadIdea2 extends Frame implements ActionListener { Button b1 = new Button("Button 1"), b2 = new Button("Button 2"); public BadIdea2() { setLayout(new FlowLayout()); addWindowListener(new WL()); b1.addActionListener(this); b2.addActionListener(this); add(b1); add(b2); } public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if(source == b1) System.out.println("Button 1 pressed"); else if(source == b2) System.out.println("Button 2 pressed"); else System.out.println("Something else"); }
class WL extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.out.println("Window Closing");
System.exit(0);
}
}
public static void main(String[] args) {
Frame f = new BadIdea2();
f.setSize(300,200);
f.setVisible(true);
}
}
Oddelenie BL a GUI
import java.awt.*;import java.awt.event.*;import java.applet.*;
class BusinessLogic { private int modifier; BusinessLogic(int mod) { modifier = mod; } public void setModifier(int mod) { modifier = mod; } public int getModifier() { return modifier; } public int calculation1(int arg) { return arg * modifier; } public int calculation2(int arg) { return arg + modifier; }}
public class Separation extends Applet { TextField t = new TextField(20), mod = new TextField(20); BusinessLogic bl = new BusinessLogic(3); Button calc1 = new Button("Calculation 1"), calc2 = new Button("Calculation 2");
public void init() { add(t); calc1.addActionListener(new Calc1L()); calc2.addActionListener(new Calc2L()); add(calc1); add(calc2); mod.addTextListener(new ModL()); add(new Label("Modifier:")); add(mod); }
static int getValue(TextField tf) { … }
class Calc1L implements ActionListener { public void actionPerformed(ActionEvent e) { t.setText(Integer.toString( bl.calculation1(getValue(t)))); } } class Calc2L implements ActionListener {…}
class ModL implements TextListener { public void textValueChanged(TextEvent e) { bl.setModifier(getValue(mod)); } }
Dynamic Eventsimport java.awt.*;import java.awt.event.*;import java.util.*;
public class DynamicEvents extends Frame { Vector v = new Vector(); int i = 0; Button b1 = new Button("Button 1"), b2 = new Button("Button 2"); public DynamicEvents() { setLayout(new FlowLayout()); b1.addActionListener(new B()); b1.addActionListener(new B1()); b2.addActionListener(new B()); b2.addActionListener(new B2()); add(b1); add(b2); } class B implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("A button was pressed"); } } class CountListener implements ActionListener { int index; public CountListener(int i) { index = i; } public void actionPerformed(ActionEvent e) { System.out.println( "Counted Listener " + index); } }
class B1 implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button 1 pressed"); ActionListener a = new CountListener(i++); v.addElement(a); b2.addActionListener(a); } } class B2 implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Button 2 pressed"); int end = v.size() -1; if(end >= 0) { b2.removeActionListener( (ActionListener)v.elementAt(end)); v.removeElementAt(end); } } } ….
Od appletu k aplikácii
. . . . . . . . .static class WL extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } // A main() for the application: public static void main(String[] args) { Button2NewB applet = new Button2NewB(); Frame aFrame = new Frame("Button2NewB"); aFrame.addWindowListener(new WL()); aFrame.add(applet, BorderLayout.CENTER); aFrame.setSize(300,200); applet.init(); applet.start(); aFrame.setVisible(true); }}
Pakovanie appletu do JARu
jar cf Button2NewB.jar *.class
<head>
<title>
Button2NewB Example Applet
</title>
</head>
<body>
<applet code="Button2NewB.class" archive="Button2NewB.jar" width=200 height=150>
</applet>
</body>
case studyprivate void paintFace(Graphics g) { g.drawImage(sadness==sad?
sadSmiley: sadness==happy?
happySmiley:boredSmiley,
(width*edge-faceSize)/2, (scoreHeight-faceSize)/2, this);
}
private Image initOneSmiley(int theSadness) { Image off = createImage(faceSize, faceSize); Graphics g = off.getGraphics(); g.setColor(Color.black); g.fillRect(0, 0, faceSize, faceSize); g.setColor(baseColor); g.fill3DRect(1, 1, faceSize-2, faceSize-2, true); g.fill3DRect(2, 2, faceSize-4, faceSize-4, true); g.setColor(Color.yellow); g.fillOval(6, 6, faceSize-12, faceSize-12); g.setColor(Color.black); g.drawOval(6, 6, faceSize-12, faceSize-12); if (theSadness==sad) { g.drawArc(10, faceSize-13,
faceSize-20, faceSize-20, 135, -100);
} else if (theSadness==happy) { g.drawArc(10, 10,
faceSize-20, faceSize-20, -35, -100); } else { g.fillRect(12, faceSize-12, faceSize-23, 1); } g.fillOval(13, 13, 2, 2); g.fillOval(faceSize-12-2, 13, 2, 2); return off; }
Minesweeper private Image initOneOffscreen(int i) {Image off = createImage(edge, edge); Graphics g = off.getGraphics(); g.setColor(i==exploded ? dangerousColor : baseColor); if (i > unexposed) { g.fillRect(0, 0, edge, edge); g.setColor(baseShadow); } else { g.fill3DRect(0, 0, edge-1, edge-1, true); g.setColor(Color.black); }; g.drawLine(edge-1, 0, edge-1, edge-1); g.drawLine(0, edge-1, edge-1, edge-1); int halfWidth = edge/2; int quarterPos = (edge-1)/4; if (i==unexposed || i==0 ) { } else if (i==mine || i==exploded) { /* A circle with four lines through it, and a highlight */ g.setColor(mineColor); g.drawLine(2, 2, edge-4, edge-4); g.drawLine(edge-4, 2, 2, edge-4); g.drawLine(halfWidth-1, 1, halfWidth-1, edge-3); g.drawLine(1, halfWidth-1, edge-3, halfWidth-1); g.fillOval(quarterPos, quarterPos, halfWidth+1, halfWidth+1); g.setColor(Color.white); g.fillOval(halfWidth-3, halfWidth-3, edge/8, edge/8); } else if (i==incorrect) { /* A diagonal cross, 3 pixels wide */
} else if (i==incorrect) { /* A diagonal cross, 3 pixels wide */ g.setColor(dangerousColor); g.drawLine(2, 2, edge-4, edge-4); g.drawLine(2, 3, edge-5, edge-4); g.drawLine(3, 2, edge-4, edge-5); g.drawLine(edge-4, 2, 2, edge-4); g.drawLine(edge-4, 3, 3, edge-4); g.drawLine(edge-5, 2, 2, edge-5); } else if (i==flagged) { /* A flag on a pole with a base */ g.setColor(dangerousColor); g.fillRect(halfWidth-4, halfWidth-5, halfWidth-4,
halfWidth-4); g.setColor(mineColor); g.drawLine(halfWidth, 3, halfWidth, edge-4); g.drawLine(5, edge-4, edge-5, edge-4); } else { /* A question mark or the adjacency count */ FontMetrics fm = this.getFontMetrics(theMainFont); int fontAscent = fm.getAscent(); String s = i==queried ? "?" : ""+i; g.setColor(i==queried ? new Color(0,0,255) : colors[i]); g.setFont(theMainFont); g.drawString(s, (edge-fm.stringWidth(s))/2,
fontAscent); }; return off; }
Be carefull
java/doc/demo/applet
public void init() { notImage = getImage(getCodeBase(), "images/o.gif"); crossImage = getImage(getCodeBase(), "images/x.gif"); addMouseListener(this); }
java/doc/demo/applet