IT/Java

자바 마우스 이벤트, MouseListener, MouseAdapter

노마드오브 2018. 8. 7. 23:54

package test;


import java.awt.Container;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;


import javax.swing.JFrame;

import javax.swing.JLabel;


public class Test4 extends JFrame {


JLabel la;

public Test4() {

setTitle("Mouse 이벤트 연습");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Container c = getContentPane();

c.setLayout(null);

la = new JLabel("Hello");

la.setLocation(30, 30);

la.setSize(50, 20);

c.add(la);


c.addMouseListener(new MyMouseListener());

setSize(250, 250);

setVisible(true);

}

class MyMouseListener implements MouseListener {


@Override

public void mouseClicked(MouseEvent e) {

System.out.println("mouseClicked");

}


@Override

public void mousePressed(MouseEvent e) {

System.out.println("mousePressed");

int x = e.getX();

int y = e.getY();

la.setLocation(x, y);

}


@Override

public void mouseReleased(MouseEvent e) {

System.out.println("mouseReleased");

}


@Override

public void mouseEntered(MouseEvent e) {

System.out.println("mouseEntered");

}


@Override

public void mouseExited(MouseEvent e) {

System.out.println("mouseExited");

}

}

public static void main(String[] args) {

new Test4();

}


}




package test;


import java.awt.Container;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

import java.awt.event.MouseWheelEvent;


import javax.swing.JFrame;

import javax.swing.JLabel;


import test.Test4.MyMouseListener;


public class Test5 extends JFrame {


JLabel la;

public Test5() {

setTitle("Mouse 이벤트 연습");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Container c = getContentPane();

c.setLayout(null);

la = new JLabel("Hello");

la.setLocation(30, 30);

la.setSize(50, 20);

c.add(la);


MyMouseAdapter l = new MyMouseAdapter();

// 이벤트 소스 : 이벤트를 발생시키는 대상.

//          (여기서는 컨텐트팬, =컨테이너, =JPanel)

// 이벤트 리스너 : 이벤트를 처리하는 객체

// 이벤트 소스에 이벤트 리스너를 연결!!

// 이벤트 소스.addXXXListener(이벤트리스너); 메소드 호출을 통해 연결! 

c.addMouseListener(l);

c.addMouseMotionListener(l);

c.addMouseWheelListener(l);

setSize(250, 250);

setVisible(true);

}

class MyMouseAdapter extends MouseAdapter {


@Override

public void mousePressed(MouseEvent e) {

System.out.println("mousePressed");

int x = e.getX();

int y = e.getY();

la.setLocation(x, y);

}


@Override

public void mouseWheelMoved(MouseWheelEvent e) {

System.out.println("mouseWheelMoved");

}


@Override

public void mouseDragged(MouseEvent e) {

System.out.println("mouseDragged");

}


@Override

public void mouseMoved(MouseEvent e) {

System.out.println("mouseMoved");

}

}

public static void main(String[] args) {

new Test5();


}


}