CJ_Slip_2B

Slip No.2

B) 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 TextField.

1. Open Notepad.

2. Type the following code:

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

    public class MouseEventDemo extends JFrame implements MouseMotionListener, MouseListener {
    private JTextField textField;

    public MouseEventDemo() {
    super("Mouse Event Demo");

    textField = new JTextField(20);
    textField.setEditable(false);

    add(textField, BorderLayout.SOUTH);

    addMouseMotionListener(this);
    addMouseListener(this);

    setSize(400, 400);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    }

    @Override
    public void mouseMoved(MouseEvent e) {
    // You can add code here if you want to handle mouse moved events
    }

    @Override
    public void mouseClicked(MouseEvent e) {
    int x = e.getX();
    int y = e.getY();
    textField.setText("Mouse Clicked at: (" + x + ", " + y + ")");
    }

    public static void main(String[] args) {
    new MouseEventDemo();
    }
    }


3. Save the file with the name MouseEventDemo.java. Make sure to select "All Files" in the "Save as type" dropdown and add the .java extension manually.

4. Open the Command Prompt.

5. Compile the Java program by typing:
javac MouseEventDemo.java

6. Run the compiled Java program by typing:
java MouseEventDemo

No comments:

Post a Comment