Interaction with users is the main role of Java, which is why Java is attractive. Users can talk to Java Applet programs through the mouse. Let’s first look at an example of responding to the mouse:
//Mouse.java
import java.awt.*;
import java.applet.*;
public class Mouse extends Applet
{
String text="";
public void paint(Graphics g)
{
g.drawString(text,20,20);
}
public boolean mouseDown(Event evt,int x,int y)//Mouse press processing function{
text="Mouse Down";
repaint();
return true;
}
public boolean mouseUp(Event evt,int x,int y)//mouse release processing function{
text="";
repaint();
return true;
}
}
When the user clicks on the program, the program will display "Mouse Down", indicating that the program responded to the mouse. Note, however, that Java does not differentiate between the left and right mouse buttons.
Let’s look at an example of keyboard response:
//Keyboard.java
import java.awt.*;
import java.applet.*;
public class Keyboard extends Applet
{
String text="";
public void paint(Graphics g)
{
g.drawString(text,20,20);}
public boolean keyDown(Event evt,int x)//Keyboard pressed processing function {
text="Key Down";
repaint();
return true;
}
public boolean keyUp(Event evt,int x)//Handling function for the keyboard to be released {
text="";
repaint();
return true;
}
}
}
When the keyboard is pressed, the program will display "Key Down" and clear the text when the keyboard is released. Using these functions, we can interact with the user using mouse and keyboard functions.