티스토리 뷰

반응형

⊙ 문제

 

다음 그림을 참고해 신호등이 프레임에 나타나도록 JPanel의 자식 클래스를 작성하시오.

 


 

⊙ 문제 접근 과정

 

fillOval() 함수를 통해 타원 안에 색을 채워 넣자


 

⊙ 문제 풀이

 

import java.awt.*;
import javax.swing.*;
public class Main extends JFrame {
    class CustomPanel extends JPanel {
        public void paintComponent(Graphics g) {
            int circleRadius = 30;
            int circleDiameter = circleRadius * 2;
            int centerX = 140;
            int centerY = 50;
            int top = centerY - circleRadius;
            int yellowLeft = centerX - circleRadius;
            int redLeft = yellowLeft - circleDiameter;
            int greenLeft = yellowLeft + circleDiameter;
            super.paintComponent(g);
            g.setColor(Color.GRAY);
            g.fillRoundRect(redLeft, top, circleDiameter * 3, circleDiameter, circleRadius, circleRadius);
            g.setColor(Color.RED);
            g.fillOval(redLeft, top, circleDiameter, circleDiameter);
            g.setColor(Color.YELLOW);
            g.fillOval(yellowLeft, top, circleDiameter, circleDiameter);
            g.setColor(Color.GREEN);
            g.fillOval(greenLeft, top, circleDiameter, circleDiameter);
        }
    }
    public Main() {
        setTitle("신호등");
        add(new CustomPanel());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 150);
        setVisible(true);
    }
    public static void main(String[] args) {
        new Main();
    }
}

 


⊙ 결과

 


⊙ 마무리

 

 

NONE

 

좋아요는 로그인하지 않아도 누를 수 있습니다!

728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함