Saturday, February 11, 2012

tracking mouse events example

I expect to need a program to inspect mouse events soon. I intend to find out how mouse events are delivered on a touch screen, when I have access to such a device. In the mean time I put together a program to display the mouse events that are visible to a java application.

package org.yi.happy.mouse;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

 * Track mouse events over a panel and log in a text area.
public class MouseTrackMain implements Runnable {
    private final JTextArea textArea;
        textArea = new JTextArea(10, 80);

    private void log(String event) {
        textArea.append(event + "\n");

    private void log(String event, MouseEvent e) {
        log(event + ": " + e);

    private MouseListener mouse = new MouseListener() {
        public void mouseClicked(MouseEvent e) {
            log("click", e);

        public void mousePressed(MouseEvent e) {
            log("pressed", e);

        public void mouseReleased(MouseEvent e) {
            log("released", e);

        public void mouseEntered(MouseEvent e) {
            log("entered", e);

        public void mouseExited(MouseEvent e) {
            log("exited", e);

    private MouseMotionListener mouseMotion = new MouseMotionListener() {
        public void mouseMoved(MouseEvent e) {
            log("moved", e);

        public void mouseDragged(MouseEvent e) {
            log("dragged", e);

    public void run() {
        JPanel blankPanel = new JPanel();
        blankPanel.setPreferredSize(new Dimension(400, 300));
        blankPanel.setBackground(new Color(0x7f, 0x7f, 0xff));

        JScrollPane scroll = new JScrollPane(textArea);

        JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT);

        JFrame window = new JFrame("Mouse Track");
        Container panel = window.getContentPane();
        panel.setLayout(new BorderLayout());



    public static void main(String[] args) {
        SwingUtilities.invokeLater(new MouseTrackMain());

This program is laid out so that there are no forward references.

No comments:

Post a Comment