Tag Archives: applet

Java Applet MouseEvents

A simple event based applet applications is described below
First importing the necessary header files
// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=”MouseEvents” width=300 height=100>
</applet>
*/
Next step is to create a class which implements the “MouseListener” and “MouseMotionListenerĀ “
public class MouseEvents extends AppletĀ implements MouseListener,
MouseMotionListener {
String msg = “”;
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = “Mouse clicked.”;
repaint();
}
Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = “Mouse entered.”;
repaint();
}
Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = “Mouse exited.”;
repaint();
}
Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = “Down”;
repaint();
}
Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = “Up”;
repaint();
}
Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = “*”;
showStatus(“Dragging mouse at ” + mouseX + “, ” + mouseY);
repaint();
}
Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus(“Moving mouse at ” + me.getX() + “, ” + me.getY());
}
Display msg in applet window at current X,Y location. This “paint” method is called when JVM execute “repaint()” function . The “paint” method will refresh the screen
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}

Applet FlowLayout Example

The FlowLayout class puts components in a row, sized at their preferred size.

Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps. The hgap and vgap arguments specify the number of pixels to put between components.

import java.applet.*;
import java.awt.*;
/*
  <applet code="FlowLayoutApplet" width=300 height=200>
  </applet>
*/

public class test extends Applet
{

  public void init()
  {
    setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
    for (int i = 0; i < 20; i++)
    {
    	add(new Button("Button" + i));
    }
  }
}

The output window look like this