본문 바로가기
JAVA/예제

[JAVA] 신호등

by JJH0100 2022. 10. 28.
728x90
반응형
package Ex01;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TrafficEx extends JFrame{
	public TrafficEx() {		
		setTitle("신호등");
		setSize(300, 500);
		add(new MyPanel());
		setDefaultCloseOperation(EXIT_ON_CLOSE);	
		setVisible(true);
	}
	public static void main(String[] args) {
		new TrafficEx();
	}
	
	class MyPanel extends JPanel implements ActionListener{
		boolean flag = false;
		private int light_number = 0;
		public MyPanel() {
			setLayout(new BorderLayout());
			JButton b = new JButton("신호등");
			b.addActionListener(this);
			add(b,BorderLayout.SOUTH);
		}
		
		@Override
		protected void paintComponent(Graphics g) {
			
			super.paintComponent(g);
			g.setColor(Color.BLACK);
			g.drawOval(100, 100, 100, 100);
			g.drawOval(100, 200, 100, 100);
			g.drawOval(100, 300, 100, 100);
			if(light_number == 0) {
				g.setColor(Color.red);
				g.fillOval(100, 100, 100, 100);
			}else if(light_number == 1) {
				g.setColor(Color.GREEN);
				g.fillOval(100, 200, 100, 100);
			}else {
				g.setColor(Color.YELLOW);
				g.fillOval(100, 300, 100, 100);
			}
			
			
		}
		
		@Override
		public void actionPerformed(ActionEvent e) {
			if(++light_number >=3)
				light_number =0;
			repaint();
			
		}
	}
}

 

클릭시

728x90
반응형

댓글