Interaction with the user is the main role of Java, but also the reason Java is attractive, users can use the mouse and Java applet Program dialog. Let's look at the example that responds 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)//鼠标按下处理函数
{
text="Mouse Down";
repaint();
return true;
}
public boolean mouseUp(Event evt,int x,int y)//鼠标松开处理函数
{
text="";
repaint();
return true;
}
}
When the user clicks on the program, the program displays "Mouse down", stating that the program responds to the mouse. Note, however, that Java does not differentiate between the left and right keys of the mouse.
Let's look at an example of how the keyboard responds:
//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)//键盘被按下的处理函数
{
text="Key Down";
repaint();
return true;
}
public boolean keyUp(Event evt,int x)//键盘被松开的处理函数
{
text="";
repaint();
return true;
}
}
}
When the keyboard is pressed, the program displays "Key down" and clears the text when the keyboard is released. With these functions, we can interact with the user with the mouse and keyboard functions.