학교/2-2학기(Java)
[13주차] 11/25(월) 강의내용
C0MPAS
2024. 11. 25. 22:34
12 그래픽
12.1 스윙 컴포넌트 그리기
- JPanel에 그리기
12.2 Graphics
- Graphics의 기능
- Color 클래스
- Font 클래스
// 예제 12-3: Color와 Font를 이용하여 문자열 그리기
import javax.swing.*;
import java.awt.*;
public class GraphicsColotFontEx extends JFrame{
private MyPanel panel = new MyPanel();
public GraphicsColotFontEx() {
setTitle("Color, Font 사용 예제");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(panel);
setSize(350, 470);
setVisible(true);
}
class MyPanel extends JPanel{
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawString("I Love Java", 30, 30);
g.setColor(new Color(255, 0, 0));
g.setFont(new Font("Arial", Font.ITALIC, 30));
g.drawString("How much?", 30, 60);
g.setColor(new Color(125, 125, 0));
for(int i=1; i<=5; i++) {
g.setFont(new Font("Jokerman", Font.ITALIC, i*10));
g.drawString("This much!", 30, 60 + i*60);
}
}
}
public static void main(String[] args) {
new GraphicsColotFontEx();
}
}
12.3 도형 그리기와 칠하기
- 도형 그리기
// 예제 12-4: Graphics의 drawLine() 메소드로 선 그리기
import javax.swing.*;
import java.awt.*;
public class GraphicsDrawLineEx extends JFrame{
private MyPanel panel = new MyPanel();
public GraphicsDrawLineEx() {
setTitle("drawLine 사용 예제");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(panel);
setSize(200, 170);
setVisible(true);
}
class MyPanel extends JPanel{
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.drawLine(20, 20, 100, 100);
}
}
public static void main(String[] args) {
new GraphicsDrawLineEx();
}
}
- 원호와 폐다각형 그리기
- 도형 칠하기
// 예제 12-5: 도형 칠하기 예
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();
}
}
12.4 이미지 그리기
- Graphics로 이미지 그리기
-> 원본의 일부분을 크기 조절하여 그리기
-> 이미지 로딩: Image 객체 생성
-> 원본 이미지의 일부분을 크기 조절하여 그리기
12.5 클리핑
12.6 스윙의 페인팅 메커니즘
- 스윙 컴포넌트들이 그려지는 과정
- repaint()
- JButton을 상속받아 새로운 버튼 생성
출처: 명품 JAVA Programming(개정 5판), 생능출판사