标签:
点击文字 鼠标拖动 文字会随鼠标拖动
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