[Java GUI] 鼠标移动事件处理示例

本程序演示了如何捕捉和处理鼠标移动和拖拽事件。当鼠标在左边面板中移动或拖拽时,右边JTextArea会显示事件类型及当前光标坐标。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.*;

public class MouseEventDemo {
	public static void main(String[] args) {
		new NewFrame("Mouse Motion Observer");
	}
}

class NewFrame extends JFrame implements MouseMotionListener {

	private static final long serialVersionUID = 1L;

	private JTextArea txtInfo = new JTextArea(50, 50);

	NewFrame(String title) {
		super(title);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JScrollPane sp = new JScrollPane(txtInfo);

		Container cp = getContentPane();
		cp.setLayout(new GridLayout(1, 2));

		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());
		panel.add(new JLabel("Mouse Motion Testing Area", JLabel.CENTER));
		panel.setBackground(Color.CYAN);

		cp.add(panel);
		cp.add(sp);

		panel.addMouseMotionListener(this);

		setSize(300, 200);
		setVisible(true);
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		txtInfo.append("Mouse Dragged (" + e.getX() + ", " + e.getY() + ")\n");
	}

	@Override
	public void mouseMoved(MouseEvent e) {
		txtInfo.append("Mouse moved (" + e.getX() + ", " + e.getY() + ")\n");
	}
}



你可能感兴趣的:(JAVA,java,string,testing,class,import)