Handling Mouse Events

Handling Mouse Events
Java program that demonstrates mouse events using MouseListener. In this example, we’ll display the mouse coordinates when the user clicks anywhere in the frame.

import java.awt.*;
import java.awt.event.*;

public class MouseEventsExample {
    public static void main(String[] args) {
        Frame frame = new Frame("Mouse Events Example");
        frame.setSize(400, 400);
        frame.setLayout(null);

        Label statusLabel = new Label("Click anywhere...");
        statusLabel.setBounds(150, 180, 150, 20);
        frame.add(statusLabel);

        // Add a MouseListener
        frame.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                statusLabel.setText("Clicked at (" + x + ", " + y + ")");
            }
        });
   // Add a WindowListener to close the program
      frame.addWindowListener(new WindowAdapter() {
                        @Override
       public void windowClosing(WindowEvent e) {
                System.exit(0); // Exit the program
               }
            });

        frame.setVisible(true);
    }
}

Handling more events
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseEventExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Mouse Event Example");
        JPanel panel = new JPanel();
        JLabel label1 = new JLabel("no event");
        JLabel label2 = new JLabel();
        JLabel label3 = new JLabel();
        JLabel label4 = new JLabel();
        JLabel label5=new  JLabel();

        MouseListener mouseListener = new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                label1.setText("mouse pressed at point: " + e.getX() + ", " + e.getY());
            }

            public void mouseReleased(MouseEvent e) {
                label2.setText("mouse released at point: " + e.getX() + ", " + e.getY());
            }

            public void mouseExited(MouseEvent e) {
                label3.setText("mouse exited through point: " + e.getX() + ", " + e.getY());
            }

            public void mouseEntered(MouseEvent e) {
                label4.setText("mouse entered at point: " + e.getX() + ", " + e.getY());
            }

            public void mouseClicked(MouseEvent e) {
                label5.setText("mouse clicked at point: " + e.getX() + ", " + e.getY() +
                        " (click count: " + e.getClickCount() + ")");
            }
        };

        panel.addMouseListener(mouseListener);
        panel.add(label1);
        panel.add(label2);
        panel.add(label3);
        panel.add(label4);
        panel.add(label5);

        frame.add(panel);
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}


Advanced Programs

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MouseEventDemo extends JPanel {

    private int lastX, lastY;
    private String eventType = "";

    public MouseEventDemo() {
        // Add mouse listener and mouse motion listener
        MouseAdapter mouseAdapter = new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                eventType = "Mouse Clicked";
                lastX = e.getX();
                lastY = e.getY();
                repaint();
            }

            @Override
            public void mouseMoved(MouseEvent e) {
                eventType = "Mouse Moved";
                lastX = e.getX();
                lastY = e.getY();
                repaint();
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                eventType = "Mouse Dragged";
                lastX = e.getX();
                lastY = e.getY();
                repaint();
            }
        };

        addMouseListener(mouseAdapter);
        addMouseMotionListener(mouseAdapter);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString(eventType + " at (" + lastX + ", " + lastY + ")", 10, 20);
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Mouse Event Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.add(new MouseEventDemo());
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(MouseEventDemo::createAndShowGUI);
    }
}


Explanation
  1. Creating the Custom JPanel (MouseEventDemo):

    • The MouseEventDemo class extends JPanel and overrides the paintComponent method to perform custom drawing.
    • It contains variables to store the last mouse coordinates and the type of mouse event.
  2. Handling Mouse Events:

    • A MouseAdapter is used to handle mouse events. This adapter is an abstract class that implements MouseListener and MouseMotionListener, providing default implementations for all methods.
    • The mouseClicked, mouseMoved, and mouseDragged methods are overridden to update the event type and coordinates, and call repaint to update the display.
  3. Drawing the Event Information:

    • The paintComponent method is overridden to draw the string that describes the last mouse event and its coordinates.
  4. Creating and Showing the GUI:

    • The createAndShowGUI method sets up the JFrame, adds the custom JPanel, and makes the frame visible.
    • The main method uses SwingUtilities.invokeLater to ensure the GUI creation and updates are handled on the Event Dispatch Thread.

This program creates a window that displays the type of mouse event (click, move, drag) and the coordinates where the event occurred. You can run this code to see how mouse events are handled in Java Swing.

This Java Swing program below demonstrates handling mouse events. Specifically, it changes the background color of the panel when the mouse is pressed and updates the mouse coordinates when the mouse is moved.

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MouseEventDemo extends JPanel {

    private int mouseX = 0;
    private int mouseY = 0;
    private Color backgroundColor = Color.WHITE;

    public MouseEventDemo() {
        MouseAdapter mouseAdapter = new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                // Change the background color when the mouse is pressed
                backgroundColor = new Color(
                    (int) (Math.random() * 255),
                    (int) (Math.random() * 255),
                    (int) (Math.random() * 255)
                );
                repaint();
            }

            @Override
            public void mouseMoved(MouseEvent e) {
                // Update mouse coordinates when the mouse is moved
                mouseX = e.getX();
                mouseY = e.getY();
                repaint();
            }
        };

        addMouseListener(mouseAdapter);
        addMouseMotionListener(mouseAdapter);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        setBackground(backgroundColor);

        g.setColor(Color.BLACK);
        g.drawString("Mouse Coordinates: (" + mouseX + ", " + mouseY + ")", 10, 20);
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Mouse Event Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.add(new MouseEventDemo());
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(MouseEventDemo::createAndShowGUI);
    }
}

Explanation
  1. Creating the Custom JPanel (MouseEventDemo):

    • MouseEventDemo extends JPanel and initializes the mouse coordinates and background color.
    • The MouseAdapter class is used to handle mouse events such as mousePressed and mouseMoved.
  2. Handling Mouse Events:

    • mousePressed(MouseEvent e): Changes the background color to a random color whenever the mouse is pressed.
    • mouseMoved(MouseEvent e): Updates the coordinates of the mouse as it moves.
  3. Drawing the Panel:

    • The paintComponent method is overridden to set the background color and draw the mouse coordinates on the panel.
    • setBackground(backgroundColor) sets the background color of the panel.
    • g.drawString("Mouse Coordinates: (" + mouseX + ", " + mouseY + ")", 10, 20) draws the mouse coordinates on the panel.
  4. Creating and Showing the GUI:

    • The createAndShowGUI method sets up the JFrame, adds the MouseEventDemo panel, and makes the frame visible.
    • The main method uses SwingUtilities.invokeLater to ensure the GUI creation and updates are handled on the Event Dispatch Thread.

This program demonstrates how to handle basic mouse events in Java Swing, such as detecting mouse clicks to change the background color and tracking mouse movement to display the coordinates.

Comments

Popular posts from this blog

KTU OOP LAB JAVA CSL 203 BTech CS S3 - Dr Binu V P

Syllabus and Practice Questions KTU OOPS Lab Java CSL 203

String Problems