The event model of Javase Learning 57:gui programming (II.)

Source: Internet
Author: User
Tags event listener gettext gety

one realizes two number sum and outputs the result

The above requirements are achieved by using the GUI programming that you have learned.

Tfmath.java Source code:

<span style= "FONT-SIZE:18PX;" >import java.awt.*;import java.awt.event.*;p ublic class Tfmath {public static void main (string[] args) {new Tfframe (). Launchframe ();}} Class Tfframe extends Frame{textfield num1, num2, num3;public void Launchframe () {num1 = new TextField (ten); num2 = new TEXTF Ield (num3) = new TextField (15); Label Lblplus = new label ("+"); Button btnequal = New button ("=");//Add Listener Btnequal.addactionlistener (new Mymonitor (NUM1.NUM2,NUM3)) on the Equals sign object; SetLayout ( New FlowLayout ()), add (NUM1), add (Lblplus), add (num2), add (btnequal), add (num3);p ack (); setvisible (True);}} Class Mymonitor implements Actionlistener{textfield Num1, num2, Num3;public mymonitor (TextField num1, TextField num2, Tex                Tfield num3) {this.num1 = num1;this.num2 = num2; this.num3 = num3;} public void actionperformed (ActionEvent e) {int n1 = Integer.parseint (Num1.gettext ()); int n2 = Integer.parseint ( Num2.gettext ()); Num3.settext ("" + (N1+N2));}} </span>
Operation Result:


The above code is optimized to reflect the design pattern of the façade mode and mediate this mode.

Optimized code:

<span style= "FONT-SIZE:18PX;" >import java.awt.*;import java.awt.event.*;p ublic class Tfmath {public static void main (string[] args) {new Tfframe (). Launchframe ();}} Class Tfframe extends Frame{textfield num1, num2, num3;public void Launchframe () {num1 = new TextField (ten); num2 = new TEXTF Ield (num3) = new TextField (15); Label Lblplus = new label ("+"); Button btnequal = New button ("=");//Add listener Btnequal.addactionlistener on the equals sign object (new Mymonitor (this)); SetLayout (new FlowLayout ()), add (NUM1), add (Lblplus), add (num2), add (btnequal), add (num3);p ack (); setvisible (True);}} Class Mymonitor implements Actionlistener{tfframe tf = Null;public mymonitor (tfframe tf) {this.tf = TF;} public void actionperformed (ActionEvent e) {int n1 = Integer.parseint (Tf.num1.getText ()); int n2 = Integer.parseint ( Tf.num2.getText ()); Tf.num3.setText ("" + (N1+N2));}} </span>

We can also use internal classes for code optimization.

Optimized code:

<span style= "FONT-SIZE:18PX;" >import java.awt.*;import java.awt.event.*;p ublic class Tfmath {public static void main (string[] args) {new Tfframe (). Launchframe ();}} Class Tfframe extends Frame{textfield num1, num2, num3;public void Launchframe () {num1 = new TextField (ten); num2 = new TEXTF Ield (num3) = new TextField (15); Label Lblplus = new label ("+"); Button btnequal = New button ("=");//Add Listener Btnequal.addactionlistener (new Mymonitor ()) on the Equals sign object; setlayout (New FlowLayout ( ), add (NUM1), add (Lblplus), add (num2), add (btnequal), add (num3);p ack (), setvisible (true);} Inner class Mymonitorprivate class Mymonitor implements ActionListener {public void actionperformed (ActionEvent e) {int N1 = Inte Ger.parseint (Num1.gettext ()); int n2 = Integer.parseint (Num2.gettext ()); Num3.settext ("" + (N1+N2));}}} </span>
Two results are the same as the first result.

For more information on the use of internal classes, refer to: Javase Introductory Learning 14:java Object-oriented class.

Use inner class Benefits:

1) You can easily access the members of the wrapper class.

2) You can more clearly organize your logic and place access to classes that should not be accessed by other classes.

When do I use internal classes?

When the class does not allow or does not require other classes for access.

For the above code, we can also optimize.

Tfmathtest.java Source code:

<span style= "FONT-SIZE:18PX;" >import java.awt.*;import java.awt.event.*;p ublic class Tfmathtest extends Frame{textfield num1; TextField num2; TextField sum;public static void Main (string[] args) {new Tfmathtest (). Launchframe (); public void Launchframe () {num1 = new TextField (); num2 = new TextField (); sum = new TextField (); Num1.setcolumns (n); num2.se                Tcolumns (Sum.setcolumns), setlayout (New FlowLayout ()),//setsize (500, 30); Label Lblplus = new label ("+"); Button btnequal = New button ("="); Btnequal.addactionlistener (new MyListener (this)); Add (NUM1); add (lblplus); Add (num2) Add (btnequal), add (sum);p ack (); setvisible (True);}}        Class MyListener implements Actionlistener{private Tfmathtest tfmt; Public MyListener (Tfmathtest tfmt) {this.tfmt = tfmt;} public void actionperformed (ActionEvent e) {String S1 = Tfmt.num1.getText (); String s2 = tfmt.num2.getText (), int i1 = Integer.parseint (s1); int i2 = Integer.parseint (s2); Tfmt.sum.setText ( String.valueof (I1 + I2));}} </span>

Two Graphics class each component has a paint (Graphics g) for drawing purposes, and the paint () method is automatically called each time the component is redrawn.

Many drawing methods are available in the graphics class, such as:

DrawRect (int x,int y,int width,int height)

Fillroundrect (int x,int y,int width,int height,int arcwidth,int archeight)

See the API documentation for more methods and usage.

Instance:

Testpaint.java Source code:

<span style= "FONT-SIZE:18PX;" >import java.awt.*;p ublic class Testpaint {public static void main (string[] args) {new Paintframe (). Launchframe ();}} Class Paintframe extends Frame {public void Launchframe () {setbounds (200,200,640,480); setvisible (true);} public void Paint (Graphics g) {Color c = g.getcolor (); G.setcolor (color.red); G.filloval (.); G.setcolor ( Color.green); G.fillrect (80,80,40,40);                Restores the color of the original brush G.setcolor (c);}} </span>

Operation Result:


three mouse event adapters

Abstract class Java.awt.event.MouseAdapter implements the class MouseListener interface, which can use its subclasses as the listener for MouseEvent,

Just rewrite the appropriate method.

For other listeners, there is also a corresponding adapter. Using an adapter avoids the need for a listener class to define an empty method.

Mechanism: The update () method is called in the Repaint () method, and the update () method calls the paint () method.

Instance:

Mymouseadapter.java Source code:

<span style= "FONT-SIZE:18PX;" >import java.awt.*;import java.awt.event.*;import java.util.*;p ublic class mymouseadapter{public static void Main (    String args[]) {new MyFrame ("drawing");                }}class MyFrame extends frame{arraylist<point> points = null;//Construction method MyFrame (String s) {super (s);                 points = new arraylist<point> ();                SetLayout (NULL);                 SetBounds (300,300,400,300);                This.setbackground (New Color (204,204,255));                SetVisible (TRUE); This.addmouselistener (New Monitor ());}                Draw round public void paint (Graphics g) {iterator<point> i = Points.iterator ();                        while (I.hasnext ()) {point P = (point) i.next ();                       G.setcolor (Color.Blue);                G.filloval (p.x,p.y,20,20);       }} public void Addpoint (point P) {///To Points object added Points.Add (p); The}}//mouseadapter class implements the MouseListener interface class Monitor extends Mouseadapter{public void mousepressed (MouseEvent e) {myframe f = (myframe) e.getsource ();    F.addpoint (New Point (E.getx (), e.gety ());//re-painting f.repaint (); }}</span>

Operation Result:

Click in the window to draw a lot of solid small circles


Four window event

The event class corresponding to the window event is windowevent, and the corresponding event listener interface is WindowListener.

The methods defined by the WindowListener interface are:


The adapter that corresponds to the WindowListener is Windowadapter, and the following example uses the adapter adapter design pattern.

Testwindowclose.java Source code:

<span style= "FONT-SIZE:18PX;" >import java.awt.*;import java.awt.event.*;p ublic class testwindowclose{public static void Main (String args[]) {NEW MyFrame55 ("Java Window");}    } Class MyFrame55 extends Frame{myframe55 (String s) {super (s);                SetLayout (null);                SetBounds (a);                This.setbackground (New Color (204, 204, 255));                SetVisible (true);                This.addwindowlistener (New Mywindowmonitor ());        }        The inner class Mywindowmonitor        //windowadapter class implements the WindowListener interface class        Mywindowmonitor extends windowadapter{ public void windowclosing (WindowEvent e) {setvisible (false);          System.exit (0);}}         </span>

Operation Result:


Using anonymous class-optimized code:

<span style= "FONT-SIZE:18PX;" >import java.awt.*;import java.awt.event.*;p ublic class testwindowclose{public static void Main (String args[]) {NEW MyFrame55 ("Java Window");}    } Class MyFrame55 extends Frame{myframe55 (String s) {     super (s);             SetLayout (null);             SetBounds (a);             This.setbackground (New Color (204, 204, 255));             SetVisible (true);            Using the anonymous method inner class     //windowadapter class implements the WindowListener interface             This.addwindowlistener (new Windowadapter () {public void Windowclosing (WindowEvent e) {setvisible (false);                        System.exit ( -1);}}             );}    } </span>

Anonymous inner class

Instance

<span style= "FONT-SIZE:18PX;" >import Java.awt.*;import java.awt.event.*;/* Example name: Use of anonymous classes in event handling * source file name: Testanonymous.java * to  : *  1. The nature and usage of anonymous classes. The benefit of defining the listener class as an anonymous class----* Further simplifies the code */public class Testanonymous {Frame f = new Frame ("Anonymous inner class test") on the basis of the inner class; TextField tf = new TextField;p ublic testanonymous () {F.add ("Press the left mouse button and drag"), "North"); F.add (TF, "South");// Use anonymous class F.addmousemotionlistener (new Mousemotionadapter () {public void mousedragged (MouseEvent e) {               String s = " Drag the mouse to the position ("+ e.getx () +", "+ e.gety () +") ";               Tf.settext (s);} public void mousemoved (MouseEvent e) {}}); F.setsize (+)    ; F.setvisible (TRUE);} public static void Main (String args[]) {   testanonymous t = new testanonymous ();}} </span>

Operation Result:


Testanonymous2.java Source file Code:

<span style= "FONT-SIZE:18PX;" >import Java.awt.*;import java.awt.event.*;/* Example name: Use of anonymous classes in event handling * source file name: Testanonymous2.java * to  point: * *. Anonymous classes can only be inner classes * *. Two ways to create an anonymous class----either inherit from the parent class, or you can implement the interface */public class TestAnonymous2 {frame F = new Frame ("Test"); TextField tf = new TextField (10); Button B1 = New button ("Start");p ublic TestAnonymous2 () {F.add (B1, "North") and F.add (TF, "South");// Use anonymous inner class B1.addactionlistener (new ActionListener () {private int i;public void actionperformed (ActionEvent e) {Tf.settext (E.getactioncommand () + ++i);    }); /use Anonymous inner class F.addwindowlistener (new Windowadapter () {public void windowclosing (WindowEvent e) {system.exit (0);}}); F.pack ();        F.setvisible (TRUE);} public static void Main (String args[]) {new TestAnonymous2 ();}} </span>
Operation Result:


Applicable occasions:

1) logic is relatively simple;

2) The code is relatively small;

five keyboard event handling

Instance:

<span style= "FONT-SIZE:18PX;" >import java.awt.*;import java.awt.event.*;p ublic class TestKey {public static void main (string[] args) {New Keyframe ( ). Launchframe ();}} Class Keyframe extends Frame {public void Launchframe () {setSize (+); setlocation (300,300); Addkeylistener (new Mykeymonitor ()); setvisible (true);} Using the inner class//keyadapter class implements the KeyListener interface class Mykeymonitor extends Keyadapter {public void keypressed (KeyEvent e) {int KeyCode = E.getkeycode ();                                                Press the UP key if (keycode = = keyevent.vk_up) {System.out.println ("Up");}}}} </span>

Operation Result:





Javase Learning 57:gui Programming Event Model (II)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.