首页 > 编程语言 > 详细

【JAVA语言程序设计基础篇】--事件驱动程序设计--鼠标事件

时间:2016-08-15 22:28:45      阅读:220      评论:0      收藏:0      [点我收藏+]


点击文字 鼠标拖动 文字会随鼠标拖动

package chapter16;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

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


@SuppressWarnings("serial")
public class MoveMessageDemo extends JFrame{

	public MoveMessageDemo(){
		MoveableMessagePanel p = new MoveableMessagePanel();
		setLayout(new BorderLayout());
		add(p);
	}
	public static void main(String[] args) {
		MoveMessageDemo frame = new MoveMessageDemo();
	    frame.setLocationRelativeTo(null); // Center the frame
	    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    frame.setTitle("AdapterDemo");
	    frame.setSize(220, 200);
	    frame.setVisible(true);

	}
	class MoveableMessagePanel extends JPanel{
		private String message = "this is a test";
		private int x = 20;
		private int y = 20;
		public  MoveableMessagePanel(){
			addMouseMotionListener(new MouseMotionListener() {
				
				@Override
				public void mouseDragged(java.awt.event.MouseEvent e) {
				    x=e.getX();
				    y=e.getY();
					repaint();
				}
				@Override
				public void mouseMoved(MouseEvent e) {
				}
			});
		}

		public MoveableMessagePanel(String string) {
			message = string;
			
			addMouseMotionListener(new MouseMotionListener() {
			
				@Override
				public void mouseDragged(java.awt.event.MouseEvent e) {
				    x=e.getX();
				    y=e.getY();
					repaint();
				}
				@Override
				public void mouseMoved(MouseEvent e) {
				}
			});
		}

		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
			g.drawString(message, x, y);
		}
	}
}

技术分享

【JAVA语言程序设计基础篇】--事件驱动程序设计--鼠标事件

原文:http://blog.csdn.net/qq_24653023/article/details/52214897

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!