JAVA–第十周之紅綠燈的類比程式

來源:互聯網
上載者:User

首感:本來沒按照課本上做,以為能做出來,但是費了好幾天都沒做出來,還是知識儲備太少了,所以又乖乖看課本。

首先是畫布類:

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();}}

 

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.