자바 예제
MouseMotionListener 이용해보자
1. 마우스에 별모양 따라 다니는 예제 import java.awt.*;
import java.awt.event.*;
class GraphicsEx2 extends Frame implements MouseMotionListener { int x = 0; int y = 0; public static void main(String[] args) { new GraphicsEx2("Graphics2"); }
public GraphicsEx2(String title){ super(title); addMouseMotionListener(this); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.exit(0); } });
// Frame 을 (100, 100) 의 위치에 width 500, heigth 500 크기로 보이게한다. setBounds(100, 100, 500, 500); setVisible(true);
}
public void paint(Graphics g ){ g.drawString("마우스를 웁직여보세요." ,10, 50); g.drawString("*" , x,y); }
public void update(Graphics g){ paint(g); }
public void mouseMoved(MouseEvent me){ x = me.getX(); y = me.getY(); repaint(); }
public void mouseDragged(MouseEvent me){} } |
2. 버튼을 누르면 별로 그림을 그릴수있는 예제
import java.awt.*; import java.awt.event.*;
class GraphicsEx4 extends Frame implements MouseMotionListener { int x =0; int y = 0; Image img = null; Graphics gImg = null;
public static void main(String args[]){ new GraphicsEx4("Graphics"); }
public GraphicsEx4(String title){ super(title); addMouseMotionListener(this); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.exit(0); } }); //frame (100, 100, 500, 500); setBounds(100,100, 500,500); setVisible(true);
img = createImage(500, 500); gImg = img.getGraphics(); gImg.drawString("왼쪽버튼을 누른 채로 마우스를 움직여보세요" , 10, 50); repaint(); }
public void paint(Graphics g){ if(img!=null) g.drawImage(img , 0 , 0, this); //가상화면에 그려진 그림을 Frame에 복사 } public void mouseMoved(MouseEvent me){}
public void mouseDragged(MouseEvent me){ if(me.getModifiersEx()==MouseEvent.BUTTON1_DOWN_MASK){ x = me.getX(); y = me.getY(); gImg.drawString("*" ,x,y); repaint(); } } } |
3. 마우스를 누르면 선으로 그림을 그릴수 있는 예제 import java.awt.*; import java.awt.event.*;
class GraphicsEx5 extends Frame implements MouseMotionListener { int x =0; int y =0; Image img = null; Graphics gImg = null;
public static void main(String args[]){ new GraphicsEx5("Graphics"); }
public GraphicsEx5(String title){ super(title); addMouseMotionListener(this); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.exit(0); } }); setBounds(100,100,500,500); setVisible(true);
img = createImage(500,500); gImg = img.getGraphics();/ gImg.drawString("왼쪽버튼을 누른채로 마우스를 움직여 보세요 ." , 10 ,50); repaint(); } public void paint(Graphics g){ if(img== null) return ; g.drawImage(img, 0, 0, this); }
public void mouseMoved(MouseEvent me){ x = me.getX(); y = me.getY(); }
public void mouseDragged(MouseEvent me){ if(me.getModifiersEx() != MouseEvent.BUTTON1_DOWN_M-*ASK) return ;
gImg.drawLine(x,y, me.getX(), me.getY()); x = me.getX(); y = me.getY();
repaint(); } } |