Java must learn the GUI programming _java

Source: Internet
Author: User
Tags anonymous class definition gettext inheritance pack

First, event monitoring

  

Test code One:

Package cn.javastudy.summary;
Import java.awt.*;

Import java.awt.event.*;
  public class Testtextfield {public static void main (String args[]) {new Myframetextfield ();
    Class Myframetextfield extends Frame {Myframetextfield () {TextField tf = new TextField ();
    Add (TF);
    Tf.addactionlistener (New Monitor3 ());
    Tf.setechochar (' * '); * * This Setechochar () method is to set the character to be displayed when the text box is entered, which is set to *, * so that any input will be displayed with *, but you can still see the input/setvisible (TRUE) when you print it.
    ;
  Pack (); All methods in the class Monitor3 implements ActionListener {/* * interface are public (common) * so copy void actionperformed from the API document (ACTI OnEvent e) should be preceded by void with public/public void actionperformed (ActionEvent e) {/* Event information is encapsulated in the object E, and the related methods of object E can be obtained
    The relevant information of the event * * TextField TF = (TextField) e.getsource (); * * GetSource () method is to get the event source, note: When you get this event source, * is to treat it as a TextField parent class to the * GetSource () method is defined as: "Public Object GETSOURC E () "The return value is an object, * so you want to cast the object to the TextField type * in a class you want to access anotherThe event source object of a class can be/System.out.println (Tf.gettext ()) by the GetSource () method, or Tf.gettext () to obtain the contents of the text box Tf.settext ("");
 Empty the contents of the text box}}

Test Code two:

 package cn.javastudy.summary;
Import java.awt.*;
Import java.awt.event.*;
    public class testactionevent2{public static void Main (String args[]) {frame f = new Frame ("Testactionevent");
    Button btn1 = New button ("Start");
    Button btn2 = New button ("Stop");
    Monitor2 m2 = new Monitor2 ();//Create Listener Object Btn1.addactionlistener (m2);
    /* A listener listens to the action of two buttons at the same time * * Btn2.addactionlistener (m2);
    Btn2.setactioncommand ("Gameover");/set the return information F.add (Btn1,borderlayout.north) after the execution click command of BTN2;
    
    F.add (Btn2,borderlayout.center);
    F.pack ();
  F.setvisible (TRUE); Class Monitor2 implements actionlistener{public void actionperformed (ActionEvent e) {System.out.println ("a But
    ton has been pressed, "+" the relative info is:\n "+e.getactioncommand" ());
    /* Use the returned Listener object E to invoke the Getactioncommand () method to get two buttons to perform the return information after the click Command separates the button that is currently operating based on the different areas of the returned information, BTN1 does not use the Setactioncommand () method to set The information returned by BTN1 is the text that appears on the button/}} 

Second, TextField event monitoring

  

Test code:

Package cn.javastudy.summary;
Import java.awt.*;

Import java.awt.event.*;
  public class Testtextfield {public static void main (String args[]) {new Myframetextfield ();
    Class Myframetextfield extends Frame {Myframetextfield () {TextField tf = new TextField ();
    Add (TF);
    Tf.addactionlistener (New Monitor3 ());
    Tf.setechochar (' * '); * * This Setechochar () method is to set the character to be displayed when the text box is entered, which is set to *, * so that any input will be displayed with *, but you can still see the input/setvisible (TRUE) when you print it.
    ;
  Pack (); All methods in the class Monitor3 implements ActionListener {/* * interface are public (common) * so copy void actionperformed from the API document (ACTI OnEvent e) should be preceded by void with public/public void actionperformed (ActionEvent e) {/* Event information is encapsulated in the object E, and the related methods of object E can be obtained
    The relevant information of the event * * TextField TF = (TextField) e.getsource (); * * GetSource () method is to get the event source, note: When you get this event source, * is to treat it as a TextField parent class to the * GetSource () method is defined as: "Public Object GETSOURC E () "The return value is an object, * so you want to cast the object to the TextField type * in a class you want to access anotherThe event source object of a class can be/System.out.println (Tf.gettext ()) by the GetSource () method, or Tf.gettext () to obtain the contents of the text box Tf.settext ("");

 Empty the contents of the text box}}

Implement a simple calculator using the TextField class

Package cn.javastudy.summary;
Import java.awt.*;

Import java.awt.event.*;
  public class Testmath {public static void main (String args[]) {new Tfframe (); }//* Here is the main completion of the Calculator element layout/class Tfframe extends Frame {tfframe () {* * * * creates 3 text boxes, specifying their initial size of 10 characters and 15 characters respectively.
    Another method of constructing the TextField class is public TextField (int columns) * * TextField NUM1 = new TextField (10);
    TextField num2 = new TextField (10);
    TextField num3 = new TextField (15);
    /* Create equal sign button btnequal = New button ("=");
    Btnequal.addactionlistener (New Mymonitor (NUM1, num2, num3));
    /* Give the equal sign button to monitor, let the click button after the response event occurred * * Label Lblplus = new label ("+");
    /* "+" is a static text, so use the Label class to create a static text object/setlayout (new FlowLayout ());
    * * To change the default BorderLayout layout of frame to FlowLayout layout/Add (NUM1);
    Add (Lblplus);
    Add (num2);
    Add (btnequal);
    Add (NUM3);
    Pack ();

  SetVisible (TRUE);

  } class Mymonitor implements ActionListener {TextField num1, num2, num3; * * * To enable the monitoring of the buttoncan also work on text boxes, * So define three object num1,num2,num3 in the custom class Mymonitor, * and define a constructor method for the Mymonitor class with three textfield types of parameters Number, * used to receive parameters from the three TextField types passed from the Tfframe class * Then assign the three TextField type parameters that are received to the three TextField types declared in this class num1,num2,num3 and then in a Ctionperformed () method inside processing num1,num2,num3/public mymonitor (TextField num1, TextField num2, TextField num3) {THIS.N
    UM1 = NUM1;
    this.num2 = num2;
  THIS.NUM3 = num3; The information about the public void actionperformed (ActionEvent e) {/* event is encapsulated in Object E, and the relevant information about the event can be obtained by means of the object e-* int n1 = Integer. parseint (Num1.gettext ());/* Num1 object calls the GetText () method to obtain its own displayed text string */int n2 = Integer.parseint (Num2.gettext ());/* Num2 Object Call G
    The Ettext () method obtains the text string itself displayed/Num3.settext ("" + (n1 + n2)),/* Num3 object calls the SetText () method to set its own display text/Num1.settext ("");
    /* After the completion of the calculation empty num1,num2 text box inside the content * * * Num2.settext ("");
    Num3.settext (string.valueof (N1+N2)); /* String with "+" connection to any type of data must be a string, * This uses an empty string to connect to the number of int type, so that you can implicitly convert the number of int type (N1+N2) to a string, * this is aA small technique for converting other underlying data types into strings.

 * can also use "string.valueof ((N1+N2))" (N1+N2) and convert to a string/}}

Classical usage in Java: Holding a reference to another class inside a class

Package cn.javastudy.summary;
Import java.awt.*;

Import java.awt.event.*;
    public class TestMath1 {public static void main (String args[]) {new Ttmyframe (). Launchframe (); /* Create the Ttmyframe object and invoke the Lauchframe () method to display the Calculator form///////////////////* Do the form interface of the calculator */class Ttmyframe extends Frame {*

  into a method * * TextField NUM1, num2, num3;
    public void Launchframe () {num1 = new TextField (10);
    num2 = new TextField (15);
    num3 = new TextField (15);
    Label Lblplus = new label ("+");
    Button btnequal = New button ("=");
    Btnequal.addactionlistener (This) (new mymonitorbtnequal);
    SetLayout (New FlowLayout ());
    Add (NUM1);
    Add (Lblplus);
    Add (num2);
    Add (btnequal);
    Add (NUM3);
    Pack ();
  SetVisible (TRUE); } * * Here is a reference to the Ttmyframe class, and then use this reference to access the member variable in the Ttmyframe class * This is much better than the previous one to access the member variables in the Ttmyframe class, because now you don't need to know ttmyframe What are the member variables in the class, * now to access the member variables within the Ttmyframe class, directly using the reference of the Ttmyframe class object to access it, * This Ttmyframe class object is like a great housekeeper, and I told the great housekeeper, I want to access those member variables inside the Ttmyframe class., * The butler's reference will go to help me find, no longer need me to find. 
  * The use of a reference to hold another class inside a class is a very typical usage * Use the obtained reference to access all members of another class within a class */class Mymonitorbtnequal implements ActionListener {

  Ttmyframe TTMF = null;
  Public mymonitorbtnequal (Ttmyframe ttmf) {THIS.TTMF = TTMF;
    public void actionperformed (ActionEvent e) {int n1 = Integer.parseint (Ttmf.num1.getText ());
    int n2 = Integer.parseint (Ttmf.num2.getText ());
    Ttmf.num3.setText ("" + (n1 + n2));
    Ttmf.num1.setText ("");
  Ttmf.num2.setText ("");

 }
}

The results of the operation are as follows:

Iii.. Internal class

  

Examples of the use of internal classes:

Package cn.javastudy.summary;
Import java.awt.*;

Import java.awt.event.*;
  public class TestMath3 {public static void main (String args[]) {new Mymathframe (). Launchframe ();

  } class Mymathframe extends Frame {TextField num1, num2, num3;
    public void Launchframe () {num1 = new TextField (10);
    num2 = new TextField (15);
    num3 = new TextField (15);
    Label Lblplus = new label ("+");
    Button btnequal = New button ("=");
    Btnequal.addactionlistener (New Mymonitor ());
    SetLayout (New FlowLayout ());
    Add (NUM1);
    Add (Lblplus);
    Add (num2);
    Add (btnequal);
    Add (NUM3);
    Pack ();
  SetVisible (TRUE); * * This mymonitor class is an internal class that defines the MyFrame class in the MyFrame class called the Mymonitor class/* The benefits of using the inner class: * The First great benefit is the unimpeded access to the outside All member variables and methods of the class (that is, the wrapper classes of the inner class) * as here are the three member variables defined in the MyFrame class (The outer Class) NUM1,NUM2,NUM3, * which can be accessed directly inside the Mymonitor (inner Class) This is equivalent to when creating an external class object The internal class object defaults to a reference to an external class object * * Private class Mymonitor implements ActionListener {public void ActionpeRformed (ActionEvent e) {int n1 = Integer.parseint (Num1.gettext ());
      int n2 = Integer.parseint (Num2.gettext ());
      Num3.settext ("" + (n1 + n2));
      Num1.settext ("");
    Num2.settext ("");

 }
  }
}

The great benefits of internal classes are:

    • You can easily access the member variables and methods of the external class definition
    • Declare a class as an inner class when it does not require other classes to access it.

Four, Graphics class

  

Test code:

Package cn.javastudy.summary;
Import java.awt.*;
    public class testpaint{public static void Main (String args[]) {new Mypaint (). Launchframe (); /* The call Paint (Graphics g) method is not displayed inside the main () method but when you create the frame form you can see the circles and rectangles drawn on the frame form, because the paint () method is a very special way to create a frame form is automatically implicitly invoked when we minimize the frame form and open it again, the paint () method is called again to draw the circles and rectangles on the frame form, which automatically calls the paint () method/} When the frame form needs to be redraw each time. Cl
    Ass Mypaint extends frame{public void Launchframe () {setbounds (200,200,640,480);
  SetVisible (TRUE); The public void paint (Graphics g) {/*paint (Graphics g) method has a Graphics type of parameter g we can think of this g as a painter, the painter holding a paintbrush in his hand we passed
    Set the color and shape of the brush to draw the various images we want./* Set the color of the brush/* G.setcolor (color.red);
    G.filloval (100,100,100,100); * Draw a solid ellipse/g.setcolor (Color.green); G.fillrect (150,200,200,200);/* Draw a solid rectangle///* The following two lines of code are written in order to write the good programming habits of the program is set the color of the brush, you should now restore the original color of the brush is equivalent to the painter after using the brush
    The colors on the brushes are cleared away./color C = g.getcolor ();
  G.setcolor (c); }
}

Run Result:

V. Mouse event Adapters

Test code:

Package cn.galc.test;

Import java.awt.*;
Import java.awt.event.*;
Import java.util.*;
public class mymouseadapter{public
 static void Main (String args[]) {
  new MyFrame ("Drawing ...");
 }

Class MyFrame extends Frame {
 ArrayList points = null;
 MyFrame (String s) {
  super (s);
  points = new ArrayList (); 
  SetLayout (null);
  SetBounds (300,300,400,300); 
  This.setbackground (New Color (204,204,255));
  SetVisible (true);
  This.addmouselistener (New Monitor ());
  }
  
  public void Paint (Graphics g) {
  Iterator i = Points.iterator ();
  while (I.hasnext ()) {point
   p = (point) I.next ();
   G.setcolor (Color.Blue);
   G.filloval (p.x,p.y,10,10);
   
  }
 
 public void Addpoint (point p) {
  points.add (p);
 }
}

Class Monitor extends Mouseadapter {public
 void mousepressed (MouseEvent e) {
  myframe f = (myframe) E.getsource ( );
  F.addpoint (New Point (E.getx (), E.gety ()));
  F.repaint ();
 }


Vi. Window Events

Test code:

Package cn.galc.test;
Import java.awt.*;
Import java.awt.event.*;
 public class testwindowclose{public static void Main (String args[]) {new Windowframe ("Close windowframe");
  } class Windowframe extends frame{public windowframe (String s) {super (s);
  SetBounds (200,200,400,300);
  SetLayout (NULL);
  SetBackground (New Color (204,204,255));
  SetVisible (TRUE);
This.addwindowlistener (New Windowmonitor ()); /* Listen to the action of this form, all the action information encapsulated into an object passed into the Listening class/This.addwindowlistener (* * In a method to define a class, this class is called the local class, also called anonymous internal classes, here's {... Code ...} The code inside is like the class body of a class, except that the class has no name, so the anonymous class is here to use the anonymous class as a Windowadapter class, and the essential meaning of this writing is equivalent to the anonymous class inheriting from the Windowadapter class, Now the new object of an anonymous class comes out and treats this object as Windowadapter to use this anonymous class out () No one knows the * * New Windowadapter () {public void windowclosing (Windo
     Wevent e) {setvisible (false);
    System.exit (-1);
 }
   }
  ); }/* This is also defined as the internal class */class Windowmonitor extends windowadapter{/*windowadapter (window Adapter) class implements the WindowListener listener interface heavy Write all the methods inside the WindowListener interface if you use the custom windowmonit directlyor class directly to implement the WindowListener interface, then you have to rewrite all the methods inside the WindowListener interface, but now only need to use one of these methods, so use the inheritance Implementation WindowListener listener interface of a subclass and
  Write this subclass of the method that you need to use this approach than the direct implementation of the WindowListener listener interface to rewrite many of the methods that can not be used to be simple and easy to use/////rewrite the windowclosing (WindowEvent e) method to be used * * 
public void windowclosing (WindowEvent e) {setvisible (FALSE);/* Set the form to not display to achieve the form close/system.exit (0);/* Normal exit/}}

 }

Seven, keyboard response event--keyevent

Test code:

Package cn.galc.test;
Import java.awt.*;
Import java.awt.event.*;
 public class testkeyevent{public static void Main (String args[]) {New Keyframe ("Keyboard response event");
   } class Keyframe extends frame{public keyframe (String s) {super (s);
   SetBounds (200,200,400,300);
   SetLayout (NULL);
   SetVisible (TRUE);
  Addkeylistener (New Keymonitor ()); }/* Defines the listener class for the custom keyboard as an internal class this listener class inherits from the Keyadapter class from the keyboard adapter Keyadapter class inheritance is also to be simple and convenient only need to rewrite the method that needs to be used, this practice is simpler than the direct implementation of the KeyListener interface , if the direct implementation of the KeyListener interface will be the KeyListener interface to rewrite all the methods, but the real use of only one method, so rewrite the other methods but it is not necessary to do without effort * * Class Keymonitor extends Ke
   yadapter{public void keypressed (KeyEvent e) {int keycode = E.getkeycode ();
   /* Use the getKeyCode () method to get the virtual code for the key./* If the virtual code of the key that is acquired is equal to the UP key is the virtual code that indicates that the key that is currently pressed is the UP key keyevent.vk_up indicates that every key in the virtual code keyboard that obtains the UP key has a These virtual codes are defined as static constants in the KeyEvent class, so you can access these static constants by using the form "class name. Static constant Name" (KeyCode = = keyevent.vk_up) {System.out.print
     ln ("You press the Up button"); The handling event for the keyboard is this: Each key corresponds to a dummy code, and when a key is pressed, the system will go to theA key corresponding to the virtual code, in order to determine the current press is the key
 

Through this article and you learn GUI programming, I hope you have a more comprehensive understanding of GUI programming, about GUI programming far more than these, but also need everyone to continue to learn.

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.