关闭

java ----- 模拟信号灯

559人阅读 评论(0) 收藏 举报
分类:

TestSignel.java

public class TestSignel {
	public static void main(String arge[]) {
		MySignal s = new MySignal();
	}
}

MyCanvas.java

import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.ImageObserver;

import javax.swing.JFrame;

class MyCanvas extends Canvas
{
	private int x, y, r;
	private Color color;
	
	public Color getColor() {
		return color;
	}

	public void setColor(Color color) {
		this.color = color;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public int getR() {
		return r;
	}

	public void setR(int r) {
		this.r = r;
	}

	MyCanvas()
	{		
		setBackground(Color.white);
		x = 300;
		y = 50;
		r = 0;
		color = Color.white;
	}
	
	public void paint(Graphics g)
	{
		g.setColor(Color.black);
		g.fillRect(290, 90, 120, 320);
		g.setColor(color);
		g.fillOval(x, y, r, r);
	}
}

public class MySignal extends JFrame implements ItemListener{
	
	Choice choice;
	MyCanvas oval;
	Panel panel;

	MySignal()
	{
		this.setTitle("我的信号灯");
		choice = new Choice();
		choice.add("无信号");
		choice.add("红");
		choice.add("黄");
		choice.add("绿");
		choice.addItemListener(this);
		oval = new MyCanvas();
		panel = new Panel();
		panel.add(choice);
		this.add(panel, BorderLayout.NORTH);
		this.add(oval, BorderLayout.CENTER);
		setBounds(300, 80, 750, 550);
		setExtendedState(Frame.MAXIMIZED_VERT);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
		validate();
	}

	public void itemStateChanged(ItemEvent e) {
		if(choice.getSelectedItem().equals("无信号"))
		{
			oval.setR(0);
			oval.repaint();
		}
		else if(choice.getSelectedItem().equals("红"))
		{
			oval.setY(100);
			oval.setR(100);
			oval.setColor(Color.red);
			oval.repaint();
		}
		else if(choice.getSelectedItem().equals("黄"))
		{
			oval.setY(200);
			oval.setR(100);
			oval.setColor(Color.yellow);
			oval.repaint();
		}
		else if(choice.getSelectedItem().equals("绿"))
		{
			oval.setY(300);
			oval.setR(100);
			oval.setColor(Color.green);
			oval.repaint();
		}
	}
}







0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:731918次
    • 积分:11768
    • 等级:
    • 排名:第1268名
    • 原创:420篇
    • 转载:267篇
    • 译文:0篇
    • 评论:36条
    文章分类
    最新评论