Dev/기타
[명품자바프로그래밍] 12장 실습문제 8번
코딩하는 백구
2020. 10. 17. 14:31
8. 마우스를 찍어 중심을 잡고 드래깅하여 높으면 원을 그리는 코드를 작성하라. [난이도 7]
- drawOval(), Vector 를 활용하라.
package ch12;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
class Circle{
int x,y,w,h;
public Circle(int x,int y,int w,int h) {
this.x=x;
this.y=y;
this.w=w;
this.h=h;
}
}
public class ex08 extends JFrame{
class MyPanel extends JPanel{
Vector<Circle> v=new Vector<Circle>();
int fromx,fromy,tox,toy;
public MyPanel() {
setLayout(null);
addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(MouseEvent e) {
fromx=e.getX();
fromy=e.getY();
System.out.println("xx");
}
@Override
public void mouseReleased(MouseEvent f) {
tox=f.getX();
toy=f.getY();
int w,h;
w=fromx-tox;
h=fromy-toy;
if(w<0) w=-w;
if(h<0) h=-h;
// ===========완전 동그란 원을 만들고 싶은 경우 =========
if(w<=h)
v.add(new Circle(fromx,fromy,w,w));
else if(w>h)
v.add(new Circle(fromx,fromy,h,h));
// ===========타원도 상관없이 만들고 싶은 경우 =========
// v.add(new Circle(fromx,fromy,w,h));
repaint();
System.out.println("yy");
}
});
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("ww");
for(int i=0;i<v.size();i++) {
Circle c=v.get(i);
setForeground(Color.MAGENTA);
g.drawOval(c.x, c.y, c.w, c.h);
}
}
}
MyPanel panel=new MyPanel();
public ex08() {
setTitle("draw circles");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(panel);
setSize(800,400);
setVisible(true);
}
public static void main(String[] args) {
new ex08();
}
}
도움이 되셨다면 왼쪽 하단에 하트 ♥ 한번 눌러주세요 :)