码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-08-15 22:29:22      阅读:251      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!