首感:本來沒按照課本上做,以為能做出來,但是費了好幾天都沒做出來,還是知識儲備太少了,所以又乖乖看課本。
首先是畫布類:
import java.awt.*;import java.awt.Canvas; import java.awt.Color; import java.awt.Graphics; class Mycanvas extends Canvas{int x,y,r;Color c2;Mycanvas(){setBackground(Color.white);} public void get(int x){this.x = x;}public void get2(int y){this.y = y;}public void get3(int r){this.r = r;}public void paint(Graphics g){g.setColor(c2);g.fillOval(x, y,2*r,2*r);}public void update(Graphics g){g.clearRect(x, y,2*r,2*r);paint(g);}}
然後是主類:
import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Wancheng extends JFrame implements ItemListener{Mycanvas w;JComboBox c; Wancheng(){ w = new Mycanvas();Panel p1 = new Panel();c = new JComboBox();c.addItem("預設訊號");c.addItem("紅燈");c.addItem("黃燈");c.addItem("綠燈");p1.add(c);add(w,BorderLayout.CENTER);add(p1,BorderLayout.NORTH);c.addItemListener(this);setBounds(350,350,550,550);setVisible(true);validate();}@Overridepublic void itemStateChanged(ItemEvent arg0) {// TODO Auto-generated method stubint d = c.getSelectedIndex();if (d == 0){w.get(100);w.get2(100);w.get3(100);
}if (d == 1){w.get(100);w.get2(100);w.get3(100);w.c2 = Color.red;w.repaint();}if (d == 2){w.get(100);w.get2(100);w.get3(100);w.c2 = Color.yellow;w.repaint();}if (d == 3){w.get(100);w.get2(100);w.get3(100);w.c2 = Color.green;w.repaint();}}}
最後是測試類別;
public class Test {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubnew Wancheng();}}