Question 5
bulb.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
public class bulb extends JFrame implements ActionListener
{
JButton b1, b2;
Signal on = new Signal(Color.blue);
public bulb()
{
super("POWER SWITCH");
getContentPane().setLayout(new GridLayout(3,5));
b1 = new JButton("ON");
b2 = new JButton("OFF");
b1.addActionListener(this);
b2.addActionListener(this);
on.turnOn(false);
JPanel p1 = new JPanel(new GridLayout(1,1));
p1.add(on);
JPanel p2 = new JPanel(new FlowLayout());
p2.add(b1);
p2.add(b2);
getContentPane().add(p1);
getContentPane().add(p2);
pack();
}
public static void main(String[] args)
{
bulb tl = new bulb();
tl.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == b1)
{
on.turnOn(true);
}
else if (e.getSource() == b2)
{
on.turnOn(false);
}
}
}
class Signal extends JPanel
{
Color on;
int radius = 30;int border = 10;
boolean change;
Signal(Color color)
{
on = color;
change = true;
}
public void turnOn(boolean a)
{
change = a;
repaint();
}
public Dimension getPreferredSize()
{
int size = (radius+border)*2;
return new Dimension( size, size );
}
public void paintComponent(Graphics g)
{
g.setColor( Color.black );
g.fillRect(0,0,getWidth(),getHeight());
if (change){
g.setColor( on );
} else {
g.setColor( on.darker().darker().darker() );
}
g.fillOval( border,border,2*radius,2*radius );
}
}