점 그리기 (연속 된 점 및 삭제)

화면에 점을 그리고 해당 점의 개수를 출력 왼쪽 마우스로 그리고 오른쪽 마우스로 지우는 기능

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.geom.Rectangle2D;

import java.awt.event.MouseEvent;
import java.util.LinkedList;
import java.util.ListIterator;


class MyJpanel extends JPanel implements MouseMotionListener, MouseListener{
    private class MyPoint{
        private int x,y;
        MyPoint(int _x, int _y){
            x = _x;
            y = _y;
        }
        void draw(Graphics g){
            g.setColor(Color.BLACK);
            g.fillOval(x, y, 3, 3);
        }
    } // 점을 그리기 위한 이너 클래스

    private class MyRect{
        private int x1,y1,x2,y2;
        int x,y,w,h;
        Color color;
        MyRect(int _x1,int _y1,int _x2,int _y2){
            x1 = _x1;
            y1 = _y1;
            x2 = _x2;
            y2 = _y2;
            color = Color.RED;
        }
        void draw(Graphics g){
            g.setColor(color);
            x = x1;
            y = y1;
            w = x2 - x1;
            h = y2 - y1;
            if(w < 0){x = x2; w = -w;}
            if(h < 0){y = y2; h = -h;}
            g.drawRect(x, y, w, h);
        }
        void setxy(int _x,int _y){
            x2 = _x;
            y2 = _y;
        }
    } // 지우개 사각형 이너 클래스 

    class Mylable extends JLabel{
        String str = "Num of Points: ";
        Mylable(){
            setText(str + '0');
        }
    } // 숫자 표시 클래스

    int mouseButton;
    LinkedList<MyPoint> points = new LinkedList<>();
    MyRect rect = null;
    Mylable lable = null;
    // 서로 연결 해줄 레퍼런스 변수

    // panel생성자
    MyJpanel(){
        addMouseListener(this);
        addMouseMotionListener(this);
        lable = new Mylable();
        add(lable);
    }
    
    public void mousePressed(MouseEvent e) {
        mouseButton = e.getButton();
        if(mouseButton == MouseEvent.BUTTON3){
            rect = new MyRect(e.getX(), e.getY(), e.getX(), e.getY());
        } //오른쪽 클릭 시 MyRcet객체 생성
    }
    public void mouseDragged(MouseEvent e) {
        if(mouseButton == MouseEvent.BUTTON1){ // 왼쪽 클릭 시 
            points.add(new MyPoint(e.getX(),e.getY())); 
            lable.setText("Num of Points: "+points.size());
            repaint();
        }
        else if(mouseButton == MouseEvent.BUTTON3){ // 오른쪽 클릭시 사각형 크기 다시 그리기
            rect.setxy(e.getX(),e.getY());
            repaint();
        }
    }
    // 마우스를 땠을 경우
    public void mouseReleased(MouseEvent e) {
        if(rect != null){
          // contains로 검사하기 위해 선언
          Rectangle2D r_rect = new Rectangle2D.Float(rect.x,rect.y,rect.w,rect.h);
          ListIterator<MyPoint> it = points.listIterator();
          for(;it.hasNext();)
          {
            MyPoint p = it.next();
            if(r_rect.contains(p.x,p.y))
            it.remove();
          }
        }
        lable.setText("Num of Points: "+points.size());
        rect = null;
        repaint();
    }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for(int i= 0; i< points.size(); i++){
            points.get(i).draw(g);
        }
        if(rect != null){
            rect.draw(g);
        }
    }
}

public class App extends JFrame{
    App(){
        setSize(700,400);
        setTitle("Point");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(new MyJpanel());
        setVisible(true);
    }
    public static void main(String[] args){
        new App();
    }
}

부족한 부분!

  • Rectangle2D를 사용하는 부분
  • ListIterator로 하나씩 검사하여 삭제 처리 부분
  • if(w < 0){x = x2; w = -w;} , if(h < 0){y = y2; h = -h;}
    • 뒤집히는 4방향 처리 부분..!

선 그리기 (연속된 선 커브)

선을 여러개 그리기 위해선 각 점을 서로 이어서 선을 그리고 해당 선을 저장하는 또다른 자료구조가 필요…!

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.awt.event.MouseEvent;
import java.util.LinkedList;


class MyJpanel extends JPanel implements MouseMotionListener, MouseListener{
    private class MyLine{ //선을 저장하는 클래스
        LinkedList<Point> points; // 내부에 링크드리스트로 Point 저장 선의 구성 요소
        MyLine(){
            points = new LinkedList<>();
        }
        void addPoint(Point x){
            points.add(x);
        }
        void draw(Graphics g){
            for(int i= 1; i< points.size(); i++){ // 처음부터 끝까지 돌면서 점끼리 이어서 그림
                g.drawLine(points.get(i - 1).x, points.get(i - 1).y, points.get(i).x, points.get(i).y);
            }
        }
    }

    class Mylable extends JLabel{
        String str = "Num of Line: ";
        Mylable(){
            setText(str + '0');
        }
    }
    //선을 저장하는 lines링크드리스트
    LinkedList<MyLine> lines;
    MyLine ptr;
    Mylable lable = null;
    int mouseButton;

    MyJpanel(){ //초기화 부분
        addMouseListener(this);
        addMouseMotionListener(this);
        lable = new Mylable();
        lines = new LinkedList<>();
        add(lable);
    }
    
    public void mousePressed(MouseEvent e) {
        mouseButton = e.getButton();
        if(mouseButton == MouseEvent.BUTTON1){
            ptr = new MyLine();
            lines.add(ptr);
        } //클릭할 경우에 MyLine 객체 생성
    }
    public void mouseDragged(MouseEvent e) {
        if(mouseButton == MouseEvent.BUTTON1){
            ptr.addPoint(e.getPoint());
            lable.setText("Num of Points: "+lines.size());
            repaint();
        } //드래그하고 있을 때 마다 해당 선 객체에 넣어줌 
    }
    public void mouseReleased(MouseEvent e) {
    }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for(MyLine e : lines){ //전체 선을 계속 그림
            e.draw(g);
        }
    }
}

public class App extends JFrame{
    App(){
        setSize(700,400);
        setTitle("Point");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(new MyJpanel());
        setVisible(true);
    }
    public static void main(String[] args){
        new App();
    }
}

부족한 부분!

  • 화면 비율 조정 부분 너무 어려움..

사각형 그리기(라디오 버튼 색 변경)

MyRect클래스를 만들고 해당 버튼에 따라 색 변경을 추가한다.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.util.LinkedList;


class MyJpanel extends JPanel implements MouseMotionListener, MouseListener{
    private class MyRect{
        int x,y,w,h;
        Color c;
        MyRect(int _x, int _y){
            x = _x;
            y = _y;
        }
        void addPoint(int _x, int _y){
            w = _x;
            h = _y;
        }
        void draw(Graphics g){
            g.setColor(c);
            g.fillRect(x, y, w, h);
            g.setColor(Color.BLACK);
            g.drawRect(x, y, w, h);
        }
    }

    class Mylable extends JLabel{
        String str = "Num of Rect: ";
        Mylable(){
            setText(str + '0');
        }
    }

    LinkedList<MyRect> rects;
    MyRect ptr;
    Mylable lable = null;
    int mouseButton;
    Color color;

    MyJpanel(){
        addMouseListener(this);
        addMouseMotionListener(this);
        lable = new Mylable();
        rects = new LinkedList<>();
        color = Color.RED;
        add(lable);
    }
    
    public void mousePressed(MouseEvent e) {
        mouseButton = e.getButton();
        if(mouseButton == MouseEvent.BUTTON1){
            ptr = new MyRect(e.getX(), e.getY());
            ptr.c = color;
            rects.add(ptr);
        }
    }
    public void mouseDragged(MouseEvent e) {
        if(mouseButton == MouseEvent.BUTTON1){
            ptr.addPoint(e.getX()-ptr.x, e.getY()-ptr.y);
            lable.setText("Num of Rect: "+rects.size());
            repaint();
        }
    }
    public void mouseReleased(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for(MyRect e : rects){
            e.draw(g);
        }
    }
}

public class App extends JFrame implements ActionListener{
    JMenuItem item1,item2,item3;
    MyJpanel p; 
    App(){
        setSize(700,400);
        setTitle("Point");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        JMenuBar mBar = new JMenuBar();

        JMenu colorMenu = new JMenu("Color");
        mBar.add(colorMenu);
        ButtonGroup group = new ButtonGroup();

        item1 = new JRadioButtonMenuItem("Red"); 
        item2 = new JRadioButtonMenuItem("bule"); 
        item3 = new JRadioButtonMenuItem("green"); 

        item1.setSelected(true);

        item1.addActionListener(this);
        item2.addActionListener(this);
        item3.addActionListener(this);

        group.add(item1);
        group.add(item2);
        group.add(item3);

        colorMenu.add(item1);
        colorMenu.add(item2);
        colorMenu.add(item3);

        setJMenuBar(mBar);

        p = new MyJpanel();
        add(p);

        setVisible(true);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == item1)
            p.color = Color.RED;
        if(e.getSource() == item2)
            p.color = Color.BLUE;
        if(e.getSource() == item3)
            p.color = Color.GREEN;
    }
    public static void main(String[] args){
        new App();
    }
}

원 그리기 (원 선택 가능)

원 선택 부분이 중점 나머지는 클래스를 만들어서 활용하기 때문에 위랑 동일함

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import java.util.LinkedList;

class MyOval{
    Point center = new Point(0,0);
    float radius = 0;
    boolean selected = false;
    void setCenter(Point pt)
	{
		center = pt;
	}
	void setRadius(Point pt)
	{
		radius = getDistance(pt);
	}
	float getDistance(Point pt)
	{
		double r = Math.sqrt((double)((pt.x-center.x)*(pt.x-center.x)+(pt.y-center.y)*(pt.y-center.y)));
		return (float)r;		
	}
    void draw(Graphics g)
	{
		if(!selected)
			g.setColor(Color.red);
		else 
			g.setColor(Color.yellow);
		
		g.fillOval((int)(center.x-radius), (int)(center.y-radius), (int)(2*radius), (int)(2*radius));
		g.setColor(Color.black);
		g.drawOval((int)(center.x-radius), (int)(center.y-radius), (int)(2*radius), (int)(2*radius));
	}
	boolean isContain(Point p)
	{
		if(getDistance(p)<radius) return true;
		return false;
	}
}

class MyJpanel extends JPanel implements MouseMotionListener, MouseListener{
    class Mylable extends JLabel{
        String str = "Num of Oval: ";
        Mylable(){
            setText(str + '0');
        }
    }

    LinkedList<MyOval> ovals;
    MyOval ptr;
    Mylable lable = null;
    int mouseButton;
    int flag;
    Point prev_p;

    MyJpanel(){
        addMouseListener(this);
        addMouseMotionListener(this);
        lable = new Mylable();
        ovals = new LinkedList<>();
        add(lable);
    }
    
    public void mousePressed(MouseEvent e) {
        mouseButton = e.getButton();
        if(mouseButton == MouseEvent.BUTTON1){
            prev_p = e.getPoint();
            flag = 0;
            for(MyOval o: ovals){
                if(o.isContain(e.getPoint())){
                    o.selected = true;
                    flag = 1;
                }
            }
            if(flag == 0){
                ptr = new MyOval();
                ptr.center = prev_p;
                ptr.radius = 0;
                ovals.add(ptr);
            }
            repaint();
        }
    }
    public void mouseDragged(MouseEvent e) {
        //if(mouseButton == MouseEvent.BUTTON1){
        if(SwingUtilities.isLeftMouseButton(e)){
            if(flag == 0){
                ovals.getLast().setRadius(e.getPoint());
            }
            else if(flag == 1){
                int dx = (int)(e.getX() - prev_p.getX());
                int dy = (int)(e.getY() - prev_p.getY());
                for(MyOval o:ovals)
                    if(o.selected)
                        o.center.translate(dx, dy);
                prev_p = e.getPoint();
            }
        }
        repaint();
    }
    public void mouseReleased(MouseEvent e) {
        if(mouseButton == MouseEvent.BUTTON1){
            for(MyOval o:ovals)
                o.selected = false;
            flag = 0;

            repaint();
        }
    }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        lable.setText("Num of Oval: "+ovals.size());
        for(MyOval e : ovals){
            e.draw(g);
        }
    }
}

public class App extends JFrame {
    MyJpanel p; 
    App(){
        setSize(700,400);
        setTitle("Oval");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        p = new MyJpanel();
        add(p);

        setVisible(true);
    }
    public static void main(String[] args){
        new App();
    }
}

부족한 부분!

  • 원에 대한 선택 부분을 해결해야 하기 때문에 따로 contains메서드와 boolean타입의 멤버필드를 만들어서 검증함

원 그리기(list사용하여 삭제)

오른쪽 패널에 클릭하여 원을 생성하고, 왼쪽 패널에서 선택하여 삭제함

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import java.util.Iterator;
import java.util.LinkedList;


class MyJpanel_1 extends JPanel{ //원 그리는 패널
    MyJpanel_2 leftJpanel;
    LinkedList<Point> points;
    int selected;

    MyJpanel_1(){
        selected = -1;
        points = new LinkedList<>(); //원에 대한 포인터를 리스트로 저장함
        addMouseListener(new MouseAdapter() { // 어뎁터 사용
            @Override
            public void mousePressed(MouseEvent e){
                points.add(e.getPoint()); //해당 위치를 넣어주고
                leftJpanel.updateList(); // 왼쪽 패널에 메서드를 실행
                repaint();
            }
        });
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        int i = 0;
        for(Point p:points){ //point에 대해서 전체적으로 검증
            if(i==selected){
                g.setColor(Color.RED);
            }
            else{
                g.setColor(Color.BLACK);
            }
            g.drawOval(p.x-30, p.y-30, 30*2, 30*2); // 원 그리는 수식..! 
            i++;
        }
    }
    void removeSelected(){
        if(selected < 0) return; // 선택된 경우
        Iterator <Point> it = points.iterator(); //삭제의 경우이기 때문에 Iterator사용해야함
        int i = 0;
        while(it.hasNext()){ //다음이 널이 아니라면
            it.next(); // 다음으로 가고
            if(i==selected){ //인덱스가 같다면
                it.remove(); // 전 it를 삭제
                break;
            }
            i++;
        }
        selected = -1; //넣어서 연속 삭제 막음
    }
}

class MyJpanel_2 extends JPanel implements ListSelectionListener{ //ListSelectionListener인터페이스
    JButton but;
    JList list;
    DefaultListModel listModel; //!중요!
    MyJpanel_1 rightJpanel;

    MyJpanel_2(){
        setBackground(Color.GRAY);
        listModel = new DefaultListModel(); //디폴트 리스트 모델을 받아옴
        list = new JList(listModel); //디폴트 모델로 사용

        list.setBorder(BorderFactory.createLineBorder(Color.BLACK,1)); //외곽선
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //단일 선택 모드
        list.addListSelectionListener(this); // 자기자신을 리스너로 등록 위에서 상속받음
        list.setPreferredSize(new Dimension(200,400)); // 크기 설정
        add(list);

        but = new JButton("Delete"); //버튼 등록
        but.addActionListener(new ActionListener(){ //무명클래스로 리스너 등록
            @Override
            public void actionPerformed(ActionEvent e) {
                rightJpanel.removeSelected(); //선택된 원 삭제 valueChanged에서 값 자동으로 업데이트
                updateList();//업데이트 호출하여 추가해줌
            }
        });
        add(but);
    }
    @Override
    public void valueChanged(ListSelectionEvent e) { //리스트의 값이 변할 때(이벤트 메서드)
       int index = list.getSelectedIndex(); // 선택된 인덱스 번호 가져옴
       rightJpanel.selected = index; // seleted를 변경
       rightJpanel.repaint(); // 다시 그림 선택한 원 색 변경
    }
    void updateList(){ //리스트 출력 부분 메서드(추가, 삭제의 경우 호출)
        listModel.clear();

        int i = 0;
        for(Point p:rightJpanel.points){
            String str = new String();
            str = i+": center("+p.x+","+p.y+")";
            listModel.addElement(str);
            i++;
        }
    }
}

public class App extends JFrame {
    MyJpanel_1 p1; 
    MyJpanel_2 p2;
    App(){
        setSize(800,500);
        setTitle("Oval");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        
        p1 = new MyJpanel_1();
        p2 = new MyJpanel_2();
        add(p1, BorderLayout.CENTER); //그리는 부분 센터 지정

        p2.setPreferredSize(new Dimension(200,500));
        add(p2, BorderLayout.WEST); // west방향 지정, setPreferredSize으로 크기 지정

        p1.leftJpanel = p2; //컴포넌트 끼리 참조해야 하기 위해 서로 연결
        p2.rightJpanel = p1;

        setVisible(true);
    }
    public static void main(String[] args){
        new App();
    }
}

타이핑

panel로 구분하여 작성한다.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Label extends JPanel{
    Label(){
        setLayout(new BorderLayout());

        JLabel label = new JLabel("Type At the Above TextField");
        JTextField textField = new JTextField();
        JTextArea textArea = new JTextArea();

        textArea.setEditable(false);

        textField.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                textField.getText();
                textArea.setText(textField.getText()+"\n"+textArea.getText());
                textField.setText("");
            }
        });
        add(textField,BorderLayout.NORTH);
        add(textArea,BorderLayout.CENTER);
        add(label,BorderLayout.SOUTH);
    }
}

public class App extends JFrame {
    App(){
        setSize(800,500);
        setTitle("Oval");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        add(new Label());

        setVisible(true);
    }
    public static void main(String[] args){
        new App();
    }
}
  • set, get구분하기
  • textField의 액션은 enter칠때 마다 실행

전자시계

쓰레드를 이용하여 sleep으로 비동기적으로 1초씩 증가하는 시계를 만든다.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Panel extends JPanel implements ActionListener{
    JButton bt1, bt2, bt3; //각 버튼에 대한 이벤트 등록에 필요 레퍼런스 변수
    int time; //총 시간 저장
    Font f; // 폰트
    Panel(){
        bt1 = new JButton("Hour");
        bt2 = new JButton("Min");
        bt3 = new JButton("Sec");
        // 다양하게 풀어볼려고 람다, 익명, 인터페이스 등 이벤트 리스너 등록
        bt1.addActionListener((e) -> {
            time+= 3600;
            repaint();
        });
        bt2.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                time += 60; 
                repaint();
            }
        });
        bt3.addActionListener(this);
        add(bt1);
        add(bt2);
        add(bt3);
        // 쓰레드는 생성자로 리스너를 받음 대부분의 경우 인터페이스 상속 후 this로 자신을 넘겨줌 간단한 경우에는 람다 사용
        Thread t = new Thread(() -> {
            while(true){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                time++;
                repaint();
            }
        });
        t.start();
        f = new Font("Arial", Font.BOLD, 100);
        setFont(f); // 폰트 적용
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        String str = new String();
        int t = time;
        int h = t / 3600; t %= 3600;
        int m = t / 60; t %= 60;
        int s = t;
        str += Integer.toString(h); // 문자열 변환 itoa
        str += ":";
        str += Integer.toString(m);
        str += ":";
        str += Integer.toString(s);
        //if(str.length() == 1)
        Dimension d = getSize();
        g.drawString(str, 10, d.height / 2);
        time %= (3600 * 24);
    }
    @Override
    public void actionPerformed(ActionEvent e){
        if(e.getSource() == bt3){
            time++;
            repaint();
        }
    }
}

public class App extends JFrame {
    App(){
        setSize(800,500);
        setTitle("time");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        add(new Panel());

        setVisible(true);
    }
    public static void main(String[] args){
        new App();
    }
}

마우스 포인터에 도형

마우스 움직임에 따라 도형을 그린다. 도형은 시간에 따라 변화

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Panel extends JPanel implements Runnable{
    Point p;
    int r;
    int dx;
    Color color;
    int flag;
    Panel(){
        flag = 0;
        Thread t = new Thread(this); // 도형 크기 변화 쓰레드
        t.start();
        Thread thread = new Thread(()-> { // 색변화 쓰레드
            while(true){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                color = new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255));
            }
        });
        thread.start();
        Thread thread2 = new Thread(() -> { // 모양 변화 쓰레드
            while(true){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                flag++;
            }
        });
        thread2.start();
        p = new Point();
        r = 0;
        dx = 2;
        addMouseMotionListener(new MouseMotionAdapter(){ // 어뎁터를 사용하여 move만 가져옴
            @Override
            public void mouseMoved(MouseEvent e) {
                p = e.getPoint();
                repaint();
            }
        });
    }

    @Override
    public void run() {
        while(true){
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            r += dx; //시간에 따라 모양 변화를 계산
            if(r > 50) {r = 50; dx = -2;}
            if(r < 0) {r = 0; dx = 2;}
            repaint();
        }
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(color);
        if(flag%2 == 0){
            g.fillOval(p.x - r, p.y - r, r * 2, r * 2);
        }
        else if(flag %2 == 1){
            g.fillRect(p.x - r, p.y - r, r * 2, r * 2);
        }
        
    }
}

public class App extends JFrame{
    App(){
        setSize(800,500);
        setTitle("m0use m.use mOuse mXuse!!!");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        add(new Panel());

        setVisible(true);
    }
    public static void main(String[] args){
        new App();
    }
}

이미지 확대

이미지를 띄우고 마우스 휠과 이동으로 확대가 가능하다.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

class Panel extends JPanel{
    Point p;
    int size = 100;
    BufferedImage img; 

    Panel(){
        p = new Point();
        try { //이미지 읽기
            img = ImageIO.read(new File("lena.jpg"));
        } catch (IOException e) {
            System.out.println("Cannot find lena.jpg!");
			System.out.println("Terminate the program.");
			System.exit(ABORT);
        }

        addMouseMotionListener(new MouseMotionAdapter(){ 
            @Override
            public void mouseMoved(MouseEvent e) {
                p = e.getPoint();
                repaint();
            }
        });
        addMouseWheelListener((e)->{ // 마우스 휠로 제어
            int rot = e.getWheelRotation();
            size += rot*5;
            if(size < 10) size = 10;
            repaint();
        });
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.drawImage(img, 0,0,null);

        int x = p.x-size/2;	if(x<0) x = 0; if(x>img.getWidth()-size) x= img.getWidth()-size;
		int y = p.y-size/2;	if(y<0) y = 0; if(y>img.getHeight()-size) y= img.getHeight()-size;	
		 
		g2.setColor(Color.red);
		g2.setStroke(new BasicStroke(3));
		g2.drawRect(x, y, size, size);	
		
		int windowSize = 300;
		g2.drawImage(img,  img.getWidth(), 0, img.getWidth()+windowSize, windowSize, 
				           x,  y,  x+size, y+size, null);
    }
    // 그림 수식..!ㅠㅠ
}

public class App extends JFrame{
    App(){
        setSize(1000,800);
        setTitle("image magic!");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        add(new Panel());

        setVisible(true);
    }
    public static void main(String[] args){
        new App();
    }
}

키보드로 상자 움직이기

키보드 리스너로 입력받아 해당 방향으로 움직임 벽에 닿으면 팅김

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Panel extends JPanel implements Runnable{
    int x = 100;
    int y = 100;
    int vx = 0;
    int vy = 0;
    int size = 50;
    int speed;

    Panel(){
        speed = 10;

        requestFocus();
		setFocusable(true);// 키보드 입력이기 때문에 포커스를 판넬이 가져야함

        Thread t = new Thread(this);
        t.start(); //쓰레드 시작

        addKeyListener(new KeyAdapter(){ // 키보드로 입력 받아서 해당 방향으로 움직임
            @Override
            public void keyPressed(KeyEvent e) {
                switch(e.getKeyCode()){
                    case KeyEvent.VK_LEFT: {vx = -speed; vy = 0; break;}
                    case KeyEvent.VK_RIGHT: {vx = speed; vy = 0; break;}
                    case KeyEvent.VK_DOWN: {vx = 0; vy = speed; break;}
                    case KeyEvent.VK_UP: {vx = 0; vy = -speed; break;} 
                    case KeyEvent.VK_SPACE: {vx = 0; vy = 0; break;}
                    default: break;
                }
            }
        });
    }

    @Override
    public void run() { // 0.03초로 실행 코루틴
        while(true){
            try {
                Thread.sleep(30);
            } catch (InterruptedException e) {
            }
            updatePosition();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.fillRect(x, y, size, size);
    } //상자를 그림

    void updatePosition(){
        Dimension d = getSize();

        x += vx;
        y += vy;

        if(x > d.width - size) {x = d.width - size; vx = -vx;} // 바향을 바꿔줌 4방향
        if(x < 0) {x = 0; vx = -vx;}
        if(y > d.height - size) {y = d.height - size; vy = -vy;}
        if(y < 0) {y = 0; vy = -vy;}

        repaint(); // paint 호출
    }
}

public class App extends JFrame{
    App(){
        setSize(1000,800);
        setTitle("move object");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        add(new Panel());

        setVisible(true);
    }
    public static void main(String[] args){
        new App();
    }
}

원형시계..?

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;

class MyPanel8 extends JPanel implements ActionListener, Runnable
{
	int time = 0;				// in second
	JButton hour, min, sec;
	JToggleButton toggle;
	
	MyPanel8()
	{
		hour = new JButton("Hour"); hour.addActionListener(this);
		min = new JButton("Min");	min.addActionListener(this);
		sec = new JButton("Sec"); 	sec.addActionListener(this);
		toggle = new JToggleButton("Digit Clock");
		toggle.addActionListener(this);
		
		add(hour);
		add(min);
		add(sec);
		add(toggle);
		
		Thread T = new Thread(this);
		T.start();
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource() == hour)
			time += 3600;
		if(e.getSource() == min)
			time += 60;
		if(e.getSource() == sec)
			time += 1;
		if(e.getSource() == toggle)
		{
			if(toggle.isSelected())
				toggle.setText("Round Clock");
			else 
				toggle.setText("Digit Clock");
			
		}
		
		time %= (3600*24);

		repaint();		
	}
	
	@Override
	protected void paintComponent(Graphics g)
	{
		super.paintComponent(g);

        Dimension d = getSize();
        
		
		int t = time;
		int h = t/3600;	t %= 3600;	h = h%24;
		int m = t/60;	t %= 60;
		int s = t;
		
		if(!toggle.isSelected())
		{
			String str = new String();
			if(h<10)
				str += "0";
			str += new Integer(h).toString() + ":";
			if(m<10)
				str += "0";
			str += new Integer(m).toString() + ":";
			if(s<10)
				str += "0";
			str += new Integer(s).toString();
			
			Font f = new Font("Arial", Font.BOLD, 100);
	        g.setFont(f);
	       	g.drawString(str, 10, (int)(d.height/2+50));
		}
		else
		{
			int offset = 50;
			int cx = d.width/2;
			int cy = d.height/2-offset;
			int r = Math.min(cx, cy);
			cy += offset;
			
			Graphics2D g2 = (Graphics2D) g;
			g2.setStroke(new BasicStroke(2));

			g2.setColor(Color.white);
			g2.fillOval(cx-r,  cy-r, 2*r, 2*r);
			g2.setColor(Color.black);
			g2.drawOval(cx-r,  cy-r, 2*r, 2*r);
					
			double x1,y1,x2,y2;
			double r1,r2;
			double theta;
			for(int i=0; i<60; i++)
			{
				theta = 360.0f/60.0f*i/180.0f*3.141592f;
				r1 = r;
				r2 = r*0.95;
				if(i%5 == 0) r2 = r*0.9;
				x1 = r1*Math.cos(theta)+cx;
				y1 = r1*Math.sin(theta)+cy;
				x2 = r2*Math.cos(theta)+cx;
				y2 = r2*Math.sin(theta)+cy;
				g2.drawLine((int)x1, (int)y1, (int)x2, (int)y2);
			}
			
			g2.setStroke(new BasicStroke(3));
			g2.setColor(Color.blue);
			
			theta = s/60.0*3.141592*2-3.141592/2;
			r1 = r*0.9;
			x1 = r1*Math.cos(theta)+cx;
			y1 = r1*Math.sin(theta)+cy;
			g2.drawLine(cx, cy, (int)x1, (int)y1);		
			
			g2.setStroke(new BasicStroke(5));
			g2.setColor(Color.green);
			
			theta = m/60.0*3.141592*2-3.141592/2;
			r1 = r*0.7;
			x1 = r1*Math.cos(theta)+cx;
			y1 = r1*Math.sin(theta)+cy;
			g2.drawLine(cx, cy, (int)x1, (int)y1);		

			g2.setStroke(new BasicStroke(9));
			g2.setColor(Color.red);
			
			theta = (h%12*60+m)/(60.0*12.0)*3.141592*2-3.141592/2;
			r1 = r*0.5;
			x1 = r1*Math.cos(theta)+cx;
			y1 = r1*Math.sin(theta)+cy;
			g2.drawLine(cx, cy, (int)x1, (int)y1);		
			
		}
		
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true)
		{
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
			time ++;
			repaint();
		}
	}
	
}

public class Example8 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		JFrame f = new JFrame();
		f.setSize(500,500);
		f.setTitle("Example 8");
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		MyPanel8 p = new MyPanel8();
		f.add(p);
		f.setVisible(true);				
	}

}

공 떨어지기

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;


class MyBall 
{
	static float ax = 0;
	static float ay = 1.0f;
	
	float x, y;
	float vx=0, vy=0;
	float r;
	float start_time;
	
	MyBall(float _x, float _y, int t)
	{
		x = _x;
		y = _y;		
		r = 10;
		start_time = t;
	}
	void update(Dimension d)
	{
		start_time -= 1;
		if(start_time>0) return;
		
		vx += ax;
		vy += ay;
		
		x+=vx;
		y+=vy;
		
		if(y>d.height - r)
		{
			y = d.height-r;
			vy = -vy*0.9f;
		}
	}
	void draw(Graphics g)
	{
		g.setColor(Color.red);
		g.fillOval((int)(x-r), (int)(y-r), (int)(2*r), (int)(2*r));
		g.setColor(Color.black);
		g.drawOval((int)(x-r), (int)(y-r), (int)(2*r), (int)(2*r));
	}
}



class MyPanel12 extends JPanel implements Runnable
{
	ArrayList<MyBall> ballList = new ArrayList<MyBall>();

	MyPanel12()
	{
		requestFocus();
		setFocusable(true);

		Thread t = new Thread(this);
		t.start();
		
		addKeyListener(new KeyAdapter()
		{
			@Override
			public void keyPressed(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_SPACE)
				{
					
					int count = ballList.size();
					ballList.clear();
					count ++;
					
					Dimension d = getSize();
					for(int i = 0; i<count; i++)
					{
						int start_time = i*5;
						int x = (int)(d.width/(float)(count+1)*(i+1));
						MyBall b = new MyBall(x, 100, start_time);
						ballList.add(b);
					}
					
				}
			}			
		});
		
		
	}
	@Override
	protected void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		
		for(MyBall b: ballList)
			b.draw(g);	
	}
	@Override
	public void run() {
		while(true)
		{
			try {
				Thread.sleep(30);
			} catch (InterruptedException e) {
			}
			
			Dimension d = getSize();
			for(MyBall b : ballList)
			{
				b.update(d);
			}
			repaint();
			
		}		
	}

}


public class Example12 {

	public static void main(String[] args) {

		JFrame f = new JFrame();
		f.setSize(800,800);
		f.setTitle("Example 12");
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		MyPanel12 p = new MyPanel12();
		f.add(p);
		f.setVisible(true);					
	}

}

태그: ,

카테고리:

업데이트:

댓글남기기