1. 程式人生 > >模擬交通訊號燈(Java)

模擬交通訊號燈(Java)

題目描述:

編寫一個窗體應用程式模擬交通訊號燈。

在視窗北邊建立一個下拉列表,該下拉列表有“紅燈”,“黃燈”,“綠燈”三個選項,在視窗的中心建立一塊畫布,當用戶在下拉列表中選擇某項時,畫布上顯示對應的訊號燈。

畫布類:

package light;

import java.awt.*;
public class SignalPanel extends Panel {
int x,y,r;
Color c2;
SignalPanel()
{
	setBackground(Color.white);
}
public void get1(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);
}
}
視窗實現:
package light;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class SignalFrame extends JFrame implements ItemListener {
	SignalPanel w;
	JComboBox choice;
	String item0 = "預設關閉", itemRed = "紅燈", itemYellow = "黃燈", itemGreen = "綠燈";
	SignalFrame() {
		w = new SignalPanel();
		Panel p1 = new Panel();
		choice = new JComboBox();
		choice.addItem(item0);
		choice.addItem(itemRed);
		choice.addItem(itemYellow);
		choice.addItem(itemGreen);
		p1.add(choice);
		add(w, BorderLayout.CENTER);
		add(p1, BorderLayout.NORTH);
		choice.addItemListener(this);
		setBounds(350, 350, 550, 550);
		setVisible(true);
		validate();
	}

	public void itemStateChanged(ItemEvent arg0) {

		int d = choice.getSelectedIndex();
		w.get1(100);
		w.get2(100);
		w.get3(100);
		if (d == 1) {
			w.c2 = Color.red;
			w.repaint();
		}
		if (d == 2) {
			w.c2 = Color.yellow;
			w.repaint();
		}
		if (d == 3) {
			w.c2 = Color.green;
			w.repaint();
		}
	}
}

測試類:
package light;

public class Text {
public static void main(String[] args)
{
	new SignalFrame();
}
}

執行結果: