Java Program to create applet to handle mouse events - IProgramX

Q.  Create an Applet which displays a message in the center of the screen. The message indicates the events taking place on the applet window. Handle events like mouse click, mouse moved, mouse dragged, mouse pressed, and key pressed. The message should update each time an event occurs. The message should give details of the event such as which mouse button was pressed, which key is pressed etc. (Hint: Use repaint(), KeyListener, MouseListener, MouseEvent method getButton, KeyEvent methods getKeyChar)

Program:

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

public class MouseApplet extends Applet
{
    JPanel p;
    JTextField t;
    String msg;
    public void init()
    {
        t=new JTextField(20);
        add(t);
        addMouseListener(new MouseAdapter()
                {
                public void mouseClicked(MouseEvent me)
                {
                msg="Mouse Clicked : X = "+me.getX() + " Y = "+me.getY();
                t.setText(msg);
                }
                });
        addMouseMotionListener(new MouseMotionAdapter()
                {
                public void mouseMoved(MouseEvent me)
                {
                msg="Mouse Moved : X = "+me.getX() +" Y = "+me.getY();
                t.setText(msg);
                }
                });
    }
}

Post a Comment

1 Comments