정리노트

[자바/java] Thread, Graphics 도형을 그리고 thread로 크기변화 본문

프로그래밍/Java

[자바/java] Thread, Graphics 도형을 그리고 thread로 크기변화

Rolen 2023. 2. 5. 20:24

package q4;
import java.awt.*;
import javax.swing.*;
import java.io.*;

public class Q4 extends JFrame {
	int x, y, width, height;
	Q4() {
		setSize(500, 300);
		x = 50; y = 50; width = 400; height = 200;
		MyPanel p = new MyPanel();
		add(p);
		Thread t = new Thread(p);
		t.start();
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	public class MyPanel extends JPanel implements Runnable{
		public void paint(Graphics g) {
			super.paint(g);
			g.setColor(Color.PINK);
			g.fillRect(x, y, width, height);
		}
		@Override
		public void run() {
			while (true) {
				if (x < 300) {
					while (x < 300) {
						repaint();
						try {
							Thread.sleep(100);
							x += 10; width -= 10;
							y += 5; height -= 5;
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				else {
					while (x > 50) {
						repaint();
						try {
							Thread.sleep(100);
							x -= 10; width += 10;
							y -= 5; height += 5;
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
	public static void main(String[] args) {
		Q4 f = new Q4();
	}
}
728x90