Pin It

How to handle Mouse Click events in Java ?.

Program to demonstrate how to handle Mouse Click events in Java.

package com.hubberspot.swing.examples;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class MouseClickEventHandling extends JFrame {

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MouseClickEventHandling().setVisible(true);
            }
        });

    }

    public MouseClickEventHandling() { 
        mouseEventHandling();
    }

    private void mouseEventHandling() {

        setSize(300, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JTextArea textArea = new JTextArea();
        textArea.setText("Browse Text Area Below !!! ");

        textArea.addMouseListener(new MouseListener() {

            @Override
            public void mouseReleased(MouseEvent e) {

                textArea.setText(" Mouse Released ... \n Position :" +
                        e.getX() +" , "+ e.getY() + "\n Click count: "+
                        e.getClickCount());

            }

            @Override
            public void mousePressed(MouseEvent e) {

                textArea.setText(" Mouse Pressed ... \n Position :" +
                        e.getX() +" , "+ e.getY() + "\n Click count: "+
                        e.getClickCount());
            }

            @Override
            public void mouseExited(MouseEvent e) {

                textArea.setText("Mouse Exited ... \n Position :" +
                        e.getX() +" , "+ e.getY());

            }

            @Override
            public void mouseEntered(MouseEvent e) {

                textArea.setText("Mouse Entered ... \n Position :" +
                        e.getX() +" , "+ e.getY());

            }

            @Override
            public void mouseClicked(MouseEvent e) {

                textArea.setText(" Mouse Clicked ... \n Position :" +
                        e.getX() +" , "+ e.getY() + "\n Click count: "+
                        e.getClickCount());
            }
        });

        getContentPane().add(textArea);        
    }

}



Output of the program : 






 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot