/*
*
*/
Import java.awt.*;
Import java.awt.event.*;
public class Mouseandevent {
Private Frame F;
Private Button but;
Private TextField TF;
Mouseandevent ()
{
Init ();
}
Initializes the graphical interface.
public void Init ()
{
F=new FRAME ("my frame");
Basic settings for frame, this method contains SetSize and setlocation.
F.setbounds (200,200,400,300);
F.setlayout (New FlowLayout ());
Defines the text box object, specifying the number of columns.
Tf=new TextField (10);
But=new button ("my button");
Before the form is displayed, add a text box.
F.add (TF);
Add a build to a frame
F.add (But);
Before the form is displayed, load the events on the form.
MyEvent ();
Show form
F.setvisible (TRUE);
}
private void MyEvent ()
{
Add a listener to a form
F.addwindowlistener (New Windowadapter () {
public void windowclosing (WindowEvent e)
{
System.exit (0);
}
});
Adds an active event to the button.
But.addactionlistener (new ActionListener () {
public void actionperformed (ActionEvent e) {
SYSTEM.OUT.PRINTLN ("Action activity");
}
});
Adds a mouse event to the button.
But.addmouselistener (New Mouseadapter () {
Mouse Entry button Event
int count=0;
int clikcount=0;
public void mouseentered (MouseEvent e)
{
System.out.println ("Mouse into the component" +count++);
}
public void mouseclicked (MouseEvent e)
{
Get mouse clicks to achieve double-click
if (E.getclickcount () ==2)
System.out.println ("Double-click Component" +clikcount++);
}
});
Adds a keyboard event for but.
But.addkeylistener (New Keyadapter () {
@Override
public void keypressed (KeyEvent e) {
KeyCode () print key name, KeyChar () the code corresponding to the print key.
Getksytext Gets the key text (String) based on the key code.
KeyEvent is the class name. The vk_escape is the static constant that corresponds to the key.
if (E.iscontroldown () &&e.getkeycode () ==keyevent.vk_enter)
System.exit (0);
SYSTEM.OUT.PRINTLN ("Combination key Run");
System.out.println (Keyevent.getkeytext (E.getkeycode ()) + "---" +e.getkeycode ());
}
});
Add keyboard events to a text box
Tf.addkeylistener (New Keyadapter () {
public void keypressed (KeyEvent e)
{
int Code=e.getkeycode ();
If the text box is entered that is not 0 to 9, it is displayed as illegal data and does not appear in the text box.
if (! ( Code>=keyevent.vk_0&&code<=keyevent.vk_9))
{
System.out.println (code+ "---illegal data");
E.consume ();
}
}
});
}
public static void Main (string[] args) {
New Mouseandevent ();
}
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java GUI (mouse keyboard event)