Design a screen in Java to handle the Mouse Events such as MOUSE_MOVED and MOUSE_CLICK and display the position of the Mouse Click in a Text Field. |EasyCoding45
Design a screen in Java to handle the Mouse Events such as MOUSE_MOVED and MOUSE_CLICK and display the position of the Mouse Click in a Text Field.
TextField, you can use the MouseListener and MouseMotionListener interfaces. Below is a simple example program that creates a JFrame with a TextField and captures both mouse moved and mouse click events.import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MouseEventDemo {
private JTextField textField;
public MouseEventDemo() {
JFrame frame = new JFrame("Mouse Event Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create a JTextField to display mouse click position
textField = new JTextField("Mouse Click Position: ");
textField.setEditable(false);
frame.add(textField, BorderLayout.SOUTH);
// Create a JPanel to capture mouse events
JPanel panel = new JPanel();
frame.add(panel);
// Add MouseListener and MouseMotionListener to the panel
panel.addMouseListener(new CustomMouseListener());
panel.addMouseMotionListener(new CustomMouseListener());
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// Custom MouseAdapter to handle mouse events
private class CustomMouseListener extends MouseAdapter {
@Override
public void mouseMoved(MouseEvent e) {
// Display mouse moved position in the TextField
textField.setText("Mouse Moved Position: (" + e.getX() + ", " + e.getY() + ")");
}
@Override
public void mouseClicked(MouseEvent e) {
// Display mouse click position in the TextField
textField.setText("Mouse Click Position: (" + e.getX() + ", " + e.getY() + ")");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MouseEventDemo());
}
}
Note: This program creates a JFrame with a TextField and a JPanel. The CustomMouseListener class extends MouseAdapter and overrides the mouseMoved and mouseClicked methods to handle the corresponding events. The mouseMoved method updates the TextField with the current mouse position when the mouse is moved, and the mouseClicked method updates the TextField when a mouse click occurs.
Compile and run this program, and you'll see a window where the TextField is updated with the mouse position information based on mouse movement and clicks.
Comments
Post a Comment