그래픽 컨텍스트
그래픽 요소
그래픽 주체 : 그림을 그리도록 프로그래밍하는 개발자 혹은 JVM
그래픽 도구 : 펜, 붓, 팔레트, 폰트 등을 의미. 자바는 Graphics 클래스로 그리기, 칠하기, 이미지 출력하기, 클리핑 등 프로그래밍에 필 요한 모든 필드와 메서드를 제공
그래픽 대상 : 그림을 그릴 수 있는 도화지 등을 의미한다. 자바에서는 AWT나 스윙의 모든 컴포넌트, 이미지가 그래픽 대상
컴포넌트의 렌더링
그래픽을 지원하는 대부분의 프로그래밍에서 컴포넌트는 GUI 시스템이 자신의 모양을 렌더링
자바에서도 모든 스윙 컴포넌트는 JVM이 다음 메서드를 호출해 자신의 모양을 렌더링한다.
이 메서드는 javax.swing.Jcomponent 클래스가 제공
protected void paintComponent(Graphics g)
커스텀 컴포넌트
class 커스텀컴포넌트 extends 스윙컴포넌트 {
...
public void paintComponent(Graphics g){
//커스텀 컴포넌트에 필요한 코드
}
}
그래픽 컨텍스트 의미
그래픽 객체를 그리는 데 필요한 정보
Graphics 클래스는 자바에서 그리기 작업을 할 때 필요한 도구로 AWT뿐만 아니라 스윙에서도 사용. 자바에서는 색상 선택 문자열 그리기, 도형 그리기, 도형 칠하기, 이미지 그리기, 클리핑 등을 지원하는 각종 메서드와 상수를 Graphics 클래스로 제공
그래픽 프로그래밍과 관련된 클래스의 계층구조

그래픽 그리기
Graphics 클래스가 사용하는 좌표 체계
절대 좌표를 사용한다.
문자열 그리기
package main;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
class MyPanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("문자열을 그려 보자!", 20, 20); // x,y 축
g.drawString("너만 그리니? 나도 그려 보자!", 50, 50);
}
}
Main() {
setTitle("문자열 그리기");
add(new MyPanel());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
색상 지정 : Color 클래스
생성자
Color(float r, float g, float b)
Color(float r, float g, float b,float a)
Color(int r, int g, int b)
Color(int r, int g, intt b)
Color(int rgb)
Color(int rgba, boolean hasalpha)
Color 클래스가 제공하는 대표적인 상수

색상 지정 : Color 클래스
void setBackground(Color c)
void setForeground(Color c)
void setColor(Color c)
package main;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main extends JFrame {
Main() {
setTitle("색상 변환하기");
JButton b = new JButton("색상 변환");
add(b);
b.addActionListener(e -> {
Color color = new Color((int) (Math.random() * 255.0), (int) (Math.random() * 255.0), (int) (Math.random() * 255.0));
b.setBackground(color);// 색상을 랜덤으로 지정
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
폰트 지정 : Font 클래스
생성자
//지정한 폰트 이름, 폰트 스타일, 폰트 크기를 사용해 폰트 객체를 생성한다.
Font(String name, int style, int size)
Font 설정
void setFont(Font font)
Font 클래스가 제공하는 상수

package main;
import java.awt.GraphicsEnvironment;
public class Main {
public static void main(String[] args) {
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontNames = e.getAvailableFontFamilyNames();
for (String s : fontNames)
System.out.println(s);
}
}
package main;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
Main() {
setTitle("폰트 설정하기");
add(new MyPanel());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 230);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
class MyPanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Font f1 = new Font("TimesRoman", Font.PLAIN, 10);
Font f2 = new Font("TimesRoman", Font.BOLD, 12);
Font f3 = new Font("TimesRoman", Font.ITALIC, 14);
Font f4 = new Font("TimesRoman", Font.BOLD + Font.ITALIC, 16);
Font f5 = new Font("Helvetica", Font.PLAIN, 18);
Font f6 = new Font("Courier", Font.PLAIN, 20);
Font f7 = new Font("Dialog", Font.PLAIN, 22);
g.setFont(f1);
g.drawString("안녕하세요 (TimesRoman Plain)", 10, 25);
g.setFont(f2);
g.drawString("안녕하세요 (TimesRoman Bold)", 10, 50);
g.setFont(f3);
g.drawString("안녕하세요 (TimesRoman Italic)", 10, 75);
g.setFont(f4);
g.drawString("안녕하세요 (TimesRoman Bold & Italic)", 10, 100);
g.setFont(f5);
g.drawString("안녕하세요 (Helvetica)", 10, 125);
g.setFont(f6);
g.drawString("안녕하세요 (Courier)", 10, 150);
g.setFont(f7);
g.drawString("안녕하세요 (Dialog)", 10, 175);
}
}
도형 그리기
- 직선
void drawLine(int x1, int y1, int x2, int y2)
void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)
package main;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
int[] x = { 155, 205, 255 };
int[] y = { 5, 50, 5 };
Main() {
setTitle("직선 그리기");
class MyPanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);//빨간색 선
g.drawLine(50, 10, 150, 50);// X축 50에서 150으로 , Y축 10에서 50으로
g.setColor(Color.BLUE);//파란색 선
g.drawPolyline(x, y, 3);//뒤에있는 숫자는 몇개의 점을 찍을지 나타냄
}
}
add(new MyPanel());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 100);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
- 사각형
void drawRect(int x, int y, int width, int height)
void drawRoundRect(int x, int y, int width, int height, int arcHeight)
void draw3DRect(int x, int y, int width, int height , boolean raised)
void fillRect(int x, int y, int width, int height)
void fillRoundRect(int x, int y, int width , int height, int arcWidth, int arcHeight)
void fill3DRect(int x, int y, int width, int hegiht, boolean raised)

package main;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
Main() {
setTitle("다양한 사각형 그리기");
add(new JPanel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.drawRect(30, 10, 50, 50);//사각형 그리기
g.drawRoundRect(120, 10, 50, 50, 30, 20);//모서리가 둥근 사각형
g.draw3DRect(210, 10, 50, 50, false);//3D False랑 true는 그림자의 방향
g.draw3DRect(300, 10, 50, 50, true);//3D
g.setColor(Color.GREEN);
g.fillRect(30, 80, 50, 50);
g.fillRoundRect(120, 80, 50, 50, 30, 20);
g.fill3DRect(210, 80, 50, 50, false);
g.fill3DRect(300, 80, 50, 50, true);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 180);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
- 타원, 호, 다각형

package main;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
Main() {
setTitle("타원, 호, 다각형 그리기");
add(new JPanel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
int x[] = { 82, 92, 112, 92, 100, 80, 55, 68, 49, 72, 82 };
int y[] = { 8, 32, 38, 50, 75, 55, 72, 45, 28, 30, 8 };
g.fillPolygon(x, y, x.length);
g.fillArc(150, 10, 50, 50, 90, 90);//
//(150, 10) 위치에서 시작하여 가로 50, 세로 50 크기의 부채꼴을 그리며,
//부채꼴의 시작 각도가 90도이고 90도까지 그리게
g.setColor(Color.BLUE);
g.fillArc(160, 10, 50, 50, 0, 90);
g.setColor(Color.YELLOW);
g.fillArc(150, 20, 50, 50, 180, 90);
g.setColor(Color.GREEN);
g.fillArc(160, 20, 50, 50, 270, 90);
g.setColor(Color.BLACK);
g.drawOval(60, 100, 50, 50);
g.drawOval(130, 100, 100, 50);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 210);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
이미지 그리기 (중요)
주요 클래스
▪ java.awt.image 클래스: 그래픽 이미지를 사각형 픽셀 이미지로 표현.
▪ java.awt.image.BufferedImage 클래스 : Image의 자식 클래스로 애플리케이션이 직접 BufferedImage 객체를 생성할 수 있고, 이미지 데이터도 조작 가능
BufferedImage img; // Image의 자식클래스이다.
try{
img= ImageIo.read(new File("파일이름.jpg")
}catch (IOException e){
}
package main;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
Main() {
setTitle("이미지 그리기");
class MyPanel extends JPanel {
BufferedImage img;
public MyPanel() {
try {
img = ImageIO.read(new File("images/myimg.jpg"));
} catch (IOException e) {
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
//g.drawImage(img, 0, 0, 150, 150, 50, 50, 150, 150, null);
}
}
add(new MyPanel());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 500);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}


package main;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
Main() {
setTitle("이미지 그리기");
class MyPanel extends JPanel {
BufferedImage img;
public MyPanel() {
try {
img = ImageIO.read(new File("images/myimg.jpg"));
} catch (IOException e) {
}
}//경로는 상대경로로 넣어야한다.
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
//g.drawImage(img, 0, 0, 150, 150, 50, 50, 150, 150, null);
}
}
add(new MyPanel());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 500);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
클리핑
실제 이미지의 필요한 부분을 꺼내기 위해 잘라내는 것
클리핑은 Graphics 클래스로 그리기를 할 때 지정된 특정 부분만 보이도록 하는 기능
클리핑을 위한 사각형 영역을 클리핑 영역이라고 부름
영역을 따로 설정하지 않으면 컴포넌트의 전체 영역이 클리핑 영역

package main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
Main() {
setTitle("이미지 그리기");
class MyPanel extends JPanel {
BufferedImage balloons, bear;
public MyPanel() {
try {
balloons = ImageIO.read(new File("images/myimg.jpg"));
bear = ImageIO.read(new File("images/myimg2.jpg"));
} catch (IOException e) {
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setClip(30, 20, 300, 500);
g.drawImage(balloons, 0, 0, null);
g.setColor(Color.RED);
g.drawRect(20, 10, 100, 100);
g.drawImage(bear, 190, 120, null);
}
}
add(new MyPanel());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(350, 600);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
스윙의 그리기 과정
스윙 컴포넌트는 모두 JComponent 클래스의 자식 객체로 JComponent 클래스의 paintComponent( ) 메서드를 호출해서 그린 다.
paintComponent( ) 메서드는 직접 호출할 수 없고, JVM이 호출하는 콜백 메서드
paintComponent( ) 메서드 요청

package main;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
Random r = new Random();
List<Rectangle> list = new ArrayList<>();
MouseEvent e;
public Main() {
setTitle("클릭할 때마다 임의의 사각형 그리기");
add(new MousePanel());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setVisible(true);
}
class MousePanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
addMouseListener(new MouseAdapter() {//마우스를 클릭했을 때
public void mousePressed(MouseEvent e) {
if (Main.this.e != null) {
if (Main.this.e.equals(e))
return;
}
int w = r.nextInt(20) + 5;
int x = r.nextInt(350);
int y = r.nextInt(150);
list.add(new Rectangle(x, y, w, w));
repaint();
Main.this.e = e;
}
});
for (int i = 0; i < list.size(); i++) {
Rectangle r = list.get(i);
int x = (int) r.getX();
int y = (int) r.getY();
int l = (int) r.getWidth();
g.drawRect(x, y, l, l);
}//화면상에 그림을 보여준다
}
}
public static void main(String[] argv) {
new Main();
}
}
'💻 Programming > Java' 카테고리의 다른 글
[JAVA] 개념 정리(2) (0) | 2023.10.15 |
---|---|
[JAVA] 개념 정리 (1) (0) | 2023.10.15 |