Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

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 : 






 
 
© 2021 Learn Java by Examples Template by Hubberspot