ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [JAVA] 그래픽 스윙 컴포넌트 그리기, paintCompnent()
    Languages/Java 2021. 5. 18. 17:53
    반응형

     

     

     

     

     

     

    스윙의 그리기 기본 철학

     모든 컴포넌트는 자신의 모양을 스스로 그린다.

     컨테이너는 자신을 그린 후, 그 위에 자식들에게 그리기 지시

     

    public void paintComponent(Graphics g)

     스윙 컴포넌트가 자신의 모양을 그리는 메소드

     JComponent의 메소드 : 모든 스윙 컴포넌트가 이 메소드를 가지고 있음

     컴포넌트가 그려져야 하는 시점마다 호출

     크기가 변경되거나, 위치가 변경되거나 컴포넌트가 가려졌던 것이 사라지는 등

     

    Graphics 객체

     java.awt.Graphics

     컴포넌트 그리기에 필요한 도구를 제공하는 객체

     색 지정, 도형 그리기, 클리핑, 이미지 그리기 등의 메소드 제공

     

     

    사용자가 원하는 모양을 그리고자 할 때

    paintComponent(Graphics g) 오버라이딩

     

    class MyComponent extends JXXX { // JXXX는 기존의 스윙 컴포넌트
    ...
    public void paintComponent(Graphics g) { // 오버라이딩
    ... 필요한 코드 작성 ..
    	}
    }

     

     

     

     

    그래픽 기반 GUI 프로그래밍

     스윙 컴포넌트를 사용하지 않고

     선, 원, 이미지 등을 직접 그려 GUI 화면을 구성하는 방식

     

    장점

     스윙 컴포넌트로 만들 수 없는 자유로운 GUI 가능

     차트, 게임 등 자유로운 모양을 표현에 효과적

     그래픽 그리기는 컴포넌트 그리기보다 빠르다

     자바의 GUI 바탕 기술을 이해하는데 도움  개발자 자신만의 컴포넌트를 창작

     

     

     

     

     

    Graphics

     

     

    Graphics의 좌표 체계

     

    Graphics의 기능

    색상 선택하기

    문자열 출력

    도형 그리기

    도형 칠하기

    이미지 출력

    클리핑

     

    문자열 그리기

    void drawString(String str, int x, int y)

    (x,y) 영역에 str 문자열 그리기

    현재 색과 현재 폰트로 출력

     

     

     

     

    예제)

     

     

    package project;
    
    import javax.swing.*;
    import java.awt.*;
    
    public class paintJPanelEx extends JFrame {
    	private MyPanel panel = new MyPanel();
    	public paintJPanelEx() {
    		setTitle("JPanel의 paintComponent() 예제");
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setContentPane(panel);
    		setSize(250,220);
    		setVisible(true);
    	}
    	
    	class MyPanel extends JPanel {
    		public void paintComponent(Graphics g) {
    			super.paintComponent(g);
    		g.setColor(Color.BLUE);
    		g.drawRect(10,10,50,50); 
    		g.drawRect(50,50,50,50);
    		g.setColor(Color.MAGENTA);
    		g.drawRect(90,90,50,50);
    		}
    }
    	
    public static void main(String [] args) {
    	new paintJPanelEx();
    	}
    }
    

     

     

    실행결과)

     

     

     

     

     

     

    Color와 Font 클래스

     

    Color

     하나의 색을 표현하는 클래스

     Red, Green, Blue 의 3 성분으로 구성

     각 성분의 크기는 0-255(8비트)

     

    생성자

     Color(int r, int g, int b)

     red(r), green(g), blue(b) 값, sRGB 색 생성

     new Color(255, 0, 0) ; // 완전 빨강색

     

     Color(int rgb)

     rgb 정수 값은 총 32비트 중 하위 24 비트 만이 유효하고 0x00rrggbb로 표현

     하위 8비트는 blue, 그 다음 상위 8 비트는 green, 그 다음 8 비트는 blue 성분

     new Color(0x0000ff00); // 완전 초록

     

    색을 사용하는 다른 방법

     Color.BLUE 등의 static 상수 활용

     

    Graphics g;
    g.setColor(new Color(255, 0, 0)); // 빨간색
    g.setColor(new Color(0x0000ff00)); // 초록색
    g.setColor(Color.YELLOW); // 노란색

     

     

    Font

     폰트를 표현하는 클래스

     

    생성자

     Font(String fontFace, int style, int size)

     fontFace는 "고딕체", "Arial" 등

     style은 Font.BOLD, Font.ITALIC , Font.PLAIN 중 하나

     size는 픽셀 단위의 크기

     

    Graphics 객체에서 색상과 폰트 설정

     void setColor(Color color)

     칠할 색을 color로 지정

     void setFont(Font font)

     폰트를 font로 지정

     

    Graphics g;
    Font f = new Font("Arial", Font.ITALIC, 30);
    g.setFont(f);
    g.setColor(Color.RED);
    g.drawString("How much", 30,30);

     

     

     

    도형그리기

    선, 타원, 사각형, 둥근 모서리 사각형, 원호, 폐다각형

     

    graphics 메소드

     

    void drawLine(int x1, int y1, int x2, int y2)
    (x1 y1)에서 (x2 y2)까지 선을 그린다
    void drawOval(int x, int y, int w, int h)
    (x, y)에서 w x h 크기의 사각형을 내접하는 타원을 그린다
    void drawRect(int x, int y, int w, int h)
    (x, y)에서 w x h 크기의 사각형을 그린다 
    void drawRoundRect(int x, int y, int w, int h, int arcWidth, int arcHeight)
    (x, y)에서 w x h 크기의 사각형을 그리되, 4개의 모서리는 arcWidth와 arcHeight를 이용하여 원호를 그린다
    
    arcWidth : 모서리 원의 수평 반지름
    arcHeight : 모서리 원의 수직 반지름

     

     

     

     

    도형 칠하기

     

     

    도형 칠하기

     도형을 그리고 내부를 칠하는 기능

     도형의 외곽선과 내부를 따로 칠하는 기능은 없다.

     도형 칠하기를 위한 메소드

     도형 그리기 메소드 명에서 draw 를 fill로 대치하면 된다. 인자는 동일

     예) drawRect() -> fillRect(), drawArc() -> fillArc()

     

    칠하기 메소드

     void fillOval(int x1, int y1, int w, int h)

     void fillRect(int x1, int y1, int w, int h)

     void fillRoundRect(int x1, int y1, int w, int h, int arcWidth, int arcHeight)

     void fillArc(int x, int y, int w, int h, int startAngle, int arcAngle)

     void fillPolygon(int []x, int []y, int n

     

     

    예제) 도형 칠하기

     

     

    package project;
    
    import javax.swing.*;
    import java.awt.*;
    
    public class GraphicsFillEx extends JFrame {
    	private MyPanel panel = new MyPanel();
    	public GraphicsFillEx() {
    		setTitle("fillXXX 사용 예제");
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		setContentPane(panel);
    		setSize(100, 350);
    		setVisible(true);
    	}
    
    	class MyPanel extends JPanel {
    		public void paintComponent(Graphics g) {
    			super.paintComponent(g);
    			g.setColor(Color.RED);
    			g.fillRect(10,10,50,50);
    			g.setColor(Color.BLUE);
    			g.fillOval(10,70,50,50);
    			g.setColor(Color.GREEN);
    			g.fillRoundRect(10,130,50,50,20,20);
    			g.setColor(Color.MAGENTA);
    			g.fillArc(10,190,50,50,0,270); 
    			g.setColor(Color.ORANGE);
    			int [] x ={30,10,30,60};
    			int [] y ={250,275,300,275};
    			g.fillPolygon(x, y, 4); 
    		}
    	}
    public static void main(String [] args) {
    		new GraphicsFillEx();
    	}
    }
    

     

     

     

    실행결과)

     

    반응형

    댓글

Designed by Tistory.