
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class J {
public static void main(String[] arg) {
JFrame frame = new JFrame();
J16 component = new J16();
frame.setBounds(0,0,400,300);
frame.add(component);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
//J14lightに、光ってない時の色を指定できるようにする
//J14lightに、on()で点灯、off()で消灯するメソッドの追加
class J16light extends J14light {
Color bgcolor;
J16light(Color color) {
//スーパークラスJ14lightのコンストラクタを実行
super(color);
}
public void setBgcolor(Color color) {
bgcolor = color;
}
//J14lightのpaintComponentを変更(オーバーライド)
public void paintComponent(Graphics g) {
if(flg)
g.setColor(color);
else
g.setColor(bgcolor);
g.fillOval(0,0,getWidth(), getHeight());
}
void on() {
setFlg(true);
repaint();
}
void off() {
setFlg(false);
repaint();
}
}
//J15とほぼ同様です
class J16 extends JComponent implements ActionListener {
JButton button;
int count;
J16light blue, yellow, red;//変更
J16() {//変更
button = new JButton("PUSH");
button.addActionListener(this);
button.setBounds(50,10,100,30);
add(button);
blue = new J16light(Color.BLUE);
blue.setBgcolor(Color.WHITE);//追加
blue.on();//変更
blue.setBounds(80,70,60,60);
add(blue);
yellow = new J16light(Color.YELLOW);
yellow.setBgcolor(Color.WHITE);//追加
yellow.setBounds(150,70,60,60);
add(yellow);
red = new J16light(Color.RED);
red.setBgcolor(Color.WHITE);//追加
red.setBounds(220,70,60,60);
add(red);
count = 0;
}
public void paintComponent(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(50,50,260,100);
}
public void actionPerformed(ActionEvent e) {
count = (++count) % 3;
//setFlgから、分かりやすいon()、off()へ変更します
switch(count) {
case 0:
blue.on();
yellow.off();
red.off();
break;
case 1:
blue.off();
yellow.on();
red.off();
break;
default:
blue.off();
yellow.off();
red.on();
}
}
}
/*
演習問題
信号の光ってないライトは、黒になるように変更してください。
*/