/* LightBulb.java */ import java.awt.*; import java.awt.event.*; import java.io.*; import java.beans.*; public class LightBulb extends Canvas implements Serializable { //Instanzvariablen protected boolean lighton; transient protected Image offimage; transient protected Image onimage; //Methoden public LightBulb() { lighton = false; initTransientState(); } //Getter/Setter Licht an/aus public void setLightOn(boolean on) { if (on != this.lighton) { this.lighton = on; repaint(); } } public boolean getLightOn() { return this.lighton; } public void toggleLight() { setLightOn(!getLightOn()); } //Implementierung der Oberfläche public void paint(Graphics g) { int width = getSize().width; int height = getSize().height; int xpos = 0; if (width > 40) { xpos = (width - 40) / 2; } int ypos = 0; if (height > 40) { ypos = (height - 40) / 2; } g.drawImage( (this.lighton ? onimage : offimage), xpos, ypos, this ); } public Dimension getPreferredSize() { return new Dimension(40, 40); } public Dimension getMinimumSize() { return new Dimension(40, 40); } //Private Methoden private void initTransientState() { offimage = getImageResource("bulb1.gif"); onimage = getImageResource("bulb2.gif"); } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); initTransientState(); } private Image getImageResource(String name) { Image img = null; try { java.net.URL url = getClass().getResource(name); img = getToolkit().createImage(url); } catch (Exception e) { System.err.println(e.toString()); } return img; } }