BulbTest2.javaimport java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
class bulb implements ActionListener
{
boolean on;
Color C;
int x, y;
int radius = 25;
String name;
public bulb()
{
C = Color.blue;
on = true;
x = 100;
y = 100;
name = "bulb";
}
public bulb(String name, int x, int y, Color C)
{
this.C = C;
this.x = x;
this.y = y;
this.name = name;
on = true;
}
public void draw(Graphics g)
{
if (on) g.setColor( C );
else g.setColor(C.darker().darker());
g.fillOval(x-radius,y-radius,2*radius,2*radius);
}
public void change_state()
{
on = !on;
}
public String toString()
{
return "bulb " + name + " " + on;
}
public void actionPerformed(ActionEvent e)
{
on = !on;
System.out.println(this);
}
}
public class BulbTest2 extends JPanel implements ActionListener
{
static final int N = 4;
JButton[] b = new JButton[N];
bulb[] bulbs = new bulb[N];
JPanel lower;
String[] names = { "one", "two", "three", "four", "five", "six", "seven" };
Color[] colors = { Color.yellow, Color.green, Color.blue,
Color.red, Color.magenta, Color.orange, Color.pink };
public BulbTest2()
{
setPreferredSize(new Dimension(20+65*N,60));
lower = new JPanel(new FlowLayout());
for (int i=0; i<N; i++) {
bulbs[i] = new bulb(names[i],30+65*i,30,colors[i]);
b[i] = new JButton(names[i]);
b[i].addActionListener(bulbs[i]);
b[i].addActionListener(this);
lower.add(b[i]);
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for (int i=0; i<N; i++) bulbs[i].draw(g);
}
public static void main(String[] args)
{
BulbTest2 panel = new BulbTest2();
JFrame app = new JFrame("Bulb Test 2");
app.getContentPane().add(panel);
app.getContentPane().add(panel.lower,BorderLayout.SOUTH);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.pack();
app.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
repaint();
}
}
Maintained by John Loomis, updated Tue Oct 01 07:47:47 2013