Notes on the _java form program collation

Source: Internet
Author: User
Tags event listener

javaswing Dynamic Add-on controls:classDynmaicbtnlistenerImplementsjava.awt.event.actionlistener{@Override Public voidactionperformed (ActionEvent e) {System.out.println ("New Button clicked."); }                }      Private voidjbutton2actionperformed (java.awt.event.ActionEvent evt) {Centervie Wpanel.setlayout (Newboxlayout (Centerviewpanel, Boxlayout.y_axis)); JButton newbtn=NewJButton ("Mydynamicbutton"); Newbtn.addactionlistener (NewDynmaicbtnlistener ());  Centerviewpanel.add (NEWBTN); //centerviewpanel.validate (); //Centerviewpanel.repaint (); centerviewpanel.revalidate (); When adding controls dynamically, you must call the layout Setup method before Add. otherwise no effect. Centerviewpanel.setlayout (Newboxlayout (Centerviewpanel, Boxlayout.y_axis)); call Centerviewpanel.validate () after add; Centerviewpanel.repaint (); or centerviewpanel.revalidate (); To refresh the redraw control. Javaswing Control Properties: Learn about the various user interface components: JButton, JLabel, JTextField, JTextArea, JComboBox, Jlist, Jcheckbox, Jradiobutton, JMenuBar, JMenu, JMenuItem, JCheckBoxMenuItem, JRadioButtonMenuItem, Jscrollbar, JScrollPane, JTabbedPane, JButton A button is a component that triggers a behavior event when clicked. Four ways to construct a button: PublicJbutton () Create an empty button PublicJButton (String text) creates a button labeled with the specified text PublicJButton (icon icon) creates a button labeled with the specified icon PublicJButton (String text,icon icon) creates a button icon labeled with the specified text and icon: is a fixed-size picture, a typical icon is smaller and is used to decorate the component. Using Class ImageIcon, you can get icons from image files, such as: Icon icon=NewImageIcon ("Photo.gif"); JButton Property Text: A label on the button, such as Jbt.settext ("OK") to the button JBT settings label. Icon: Icons on the button, such as Available Jbt.settexticon (NewImageIcon ("A.gif")). Mnemonic: Specifies the hotkey. Pressing the ALT key and specifying the hotkey is the equivalent of pressing the button. For example, use Jbt.setmnemonic (' O ') to set O as the Hotkey for button JBT. HorizontalAlignment: This property has only three values of Swingconstants.left,swingconstants.center, Swingconstants.right. It specifies the horizontal alignment of the label on the button. The default value is centered. VerticalAlignment: This property also takes three values of Swingconstants.top, Swingconstants.center, and Swingconstants.bottom. It specifies the vertical alignment of the label on the button. The default value is centered. Horizontaltextposition: This property has a value of three swingconstants.left, Swingconstants.center, Swingconstants.right. It specifies the horizontal position of the text relative to the icon, and defaults to Swingconstants.right. corresponding method sethorizontaltextposition. Verticaltextposition: This property has a value of three swingconstants.top, Swingconstants.center, Swingconstants.bottom. It specifies the vertical position of the text relative to the icon, and the default value is Swingconstants.center. corresponding method setverticaltextposition. Second, the JLabel tag is to display a small paragraph of text, a picture or both areas. Its six construction methods are as follows: PublicJLabel () creates an empty label.  PublicJLabel (String text,intHorizontalAlignment) Creates a label that specifies the content string and horizontal alignment. Where horizontal alignment is desirable value swingconstants.left, Swingconstants.center, Swingconstants.right.  PublicJLabel (String text) creates a label for the specified text.  PublicJLabel (icon icon) creates a label for the specified icon.  PublicJLabel (icon icon,intHorizontalAlignment) Creates a label that specifies the icon and horizontal alignment.  PublicJLabel (String Text,icon Icon,intHorizontalAlignment) Creates a label that specifies text, icons, and horizontal alignment. For example, the following statement creates a label with text content of "Interest rate": JLabel myLabel=NewJLabel ("Interest rate"); The following statement creates a label that uses the file "images/map.gif "image as Icon: JLabel Maplabel=NewJLabel (NewImageIcon ("images/map.gif "); The JLabel property JLabel inherits all the properties of the class JComponent and has many properties of the JButton class, such as: Text icon HorizontalAlignment verticalalignment three, JTextField A text field is an input area where a user can enter characters. Allows the user to enter various data, such as name and description text. Four construction methods for JTextField: PublicJTextField () Creates an empty text field.  PublicJTextField (intcolumns) Creates an empty text field that specifies the number of columns.  PublicJTextField (String text) creates a text field with the specified initial text.  PublicJTextField (String text,intcolumns) creates a text field and initializes it with the specified text and number of columns. JTextField Property In addition to the text, HorizontalAlignment and other properties, JTextField has the following properties: Editable Boolean property, indicating whether the user can modify the text field. Columns the width of the text field. The JTextField Method GetText () returns a string from the text field. SetText (string text) writes the given string to the text field seteditable (Booleaneditable) makes the text field editable, which is true by default. SetColumns (intsets the number of columns in the text and the length of the text field is variable. Iv. JTextArea If you want to allow users to enter multiple lines of text, only by creating multiple JTextField instances, a better way to solve the problem is to use JTextField, which allows the user to enter multiple lines of text. Three construction methods for JTextArea: PublicJTextArea () creates an empty text area. JTextArea (intRowsintcolumns) Creates a text area that specifies the number of rows and columns. JTextArea (String s,intRowsintcolumns) Creates a text area that specifies the number of text, number of rows, and columns. JTextArea properties In addition to text, editable, columns, JTextArea has the following properties: Linewrap wrapstyleword rows LineCount tabsize JTextArea method The following methods are used to insert, append, and replace text: Public voidInser (String S,intPOS) Inserts the string s into the text area at the specified position of POS.  Public voidAppend (string s) adds the string s to the end of the text.  Public voidReplacerange (String S,intStartintend) replaces the text from position start to end with the string s. JComboBox groups and boxes are simple lists of items that users can choose from. Two construction methods for JComboBox: PublicJComboBox () The default constructor method.  PublicJComboBox (object[] stringitems) is constructed with a string list, where Stringitems is a string number ancestor. A useful property of the JComboBox property JComboBox: The SelectedIndex int value that represents the ordinal of the selected item in the combo box. The SelectedItem object type that represents the selected item. A useful way to JComboBox a method: Public voidAddItem (object Item) Adds an option in the groups and boxes, which can be any object.  PublicObject Getitemat (intindex) Gets the item of the specified ordinal in the combo box.  Public voidRemoveItem (Object anobject) deletes the specified item.  Public voidRemoveAllItems () deletes all items in the list. The role of the JList list box is basically the same as a combo box, but it allows the user to select multiple items at the same time. JList Two construction methods: JList () Creates an empty list box JList (object[] stringitems) creates a list box with an initial entry JList does not automatically scroll. To add a scroll bar to a list box is the same as the text area, just create a scroll pane and add the list box to it. JList Properties Selectedindexd selectedindices selectedvalue selectedvalues selectionmode visiblerowcount vii. JCheckBox A checkbox is a component of a user's ability to turn options on and off, like a light switch. Seven construction methods for Jcheckbox: Jcheckbox () Jcheckbox (string text) Jcheckbox (string text,Booleanselected) Jcheckbox (icon icon) Jcheckbox ( icon icon,Booleanselected) Jcheckbox (string text, icon icon) jcheckbox (string text, icon icon,Booleanselected) The properties of Jcheckbox Jcheckbox in addition to all properties that have JButton such as text, icon, mnemonic, VerticalAlignment, HorizontalAlignment, In addition to Horizontaltextposition and Verticaltextposition, there are selected properties that indicate whether the check box is selected. The Jradiobutton radio button, or the Select button, lets the user select a unique option from a set of components. Seven construction methods for Jradiobutton: Jradiobutton () Jradiobutton (string text) Jradiobutton (string text,Booleanselected) Jradiobutton (icon icon) Jradiobutton ( icon icon,Booleanselected) Jradiobutton (string text, icon icon) Jradiobutton (string text, icon icon,Booleanselected) The properties of the Jradiobutton Jradiobutton except for all properties that have JButton, such as text, icon, mnemonic, VerticalAlignment, HorizontalAlignment, Horizontaltextposition, Verticaltextposition, also has a selected property that indicates whether the radio button is selected. Combine the radio button Group radio button to add to the container like a button. To group radio buttons, you need to create an instance of Java.swing.ButtonGroup and add a radio button to the instance using the Add method, such as: Buttongroup BTG=NewButtongroup (); Btg.add (JRB1); Btg.add (JRB2); The preceding code creates a radio button group so that JRB1 and JRB2 cannot be selected at the same time. IX. The message dialog box is typically used as a temporary window to accept additional information from the user or to prompt the user for an event. A message dialog box is a simple but frequently used dialog box that displays a message to remind the user. The message dialog box is modal, meaning that no other windows are available until the message dialog box disappears. The Create Message dialog box uses the static method in the Joptionpane class: Showmessagedialog (Component parentcomponent, Object message, String title,intMessageType) Parentcomponet is the parent component of the dialog box, which is derived from it. The message is the object to be displayed, which is usually a string. Title is the caption of the dialog box. The MessageType determines the type of message that is displayed. Showmessagedialog (Component parentcomponent, Object message, String title,intmessageType, icon icon) in addition to Plain_message, each message has corresponding icons, the above method can support self-made icons. Javaswing Registration Event: Swing is an indispensable window tool group in Java and a powerful tool for building graphical user interface (GUI) programs. The Java swing component automatically generates various events to respond to user behavior. Java encapsulates events into event classes and defines an event listener for each event class. A component registers an event listener method that indicates that the component responds to a specified event.          This means that we can monitor the event generated by the event source by registering the listener to handle the user behavior we need to handle in the event handler. The general steps for handling individual component events in Java swing are:1.          Create a new component. 2.          Add the component to the appropriate panel. 3. Registering listeners to listen for events generated by event sources4. Defines the method that handles the event. Registering events we generally use two ways: one is to use a listener and multiple if statements to determine which component generated the event, and the other is to use multiple internal classes to respond to various events generated by different components, it is divided into two ways, one is the use of anonymous internal classes, one is the use of general internal classes. Here are three ways to register an event. To illustrate how the above three ways to implement the event processing method. One, the use of a listener multiple if statements to implement in this way: we want to inherit the ActionListener interface, and to implement the Actionperformed method. Gets the event source for the event through the Getactioncommand () method. [Java] View plain copy Public classTest_01extendsJFrameImplementsActionListener {test_01 () {JPanel panel=NewJPanel (); JButton button1=NewJButton ("button One"); JButton Button2=NewJButton ("button Two");          Panel.add (button1);          Panel.add (button2);  This. Getcontentpane (). Add (panel);  This. setvisible (true); Button1.addactionlistener ( This); Button2.addactionlistener ( This); }       Public voidactionperformed (ActionEvent e) {String source=E.getactioncommand (); if(Source.equals ("button One") {System.out.println ("You pressed the button one."); }          if(Source.equals ("button Two") {System.out.println ("You pressed the button two."); }  }       Public Static voidMain (String args[]) {Newtest_01 (); The disadvantage of using a listener to handle an event is that it is a good way to handle events in a relatively small amount of time, which is simple. When the program is more complex, a large set of if statements are required to implement. The Code of the program is more difficult to read and maintain. First, the use of anonymous internal classes to implement the [Java] view plain copy Public classTest_02extendsjframe{test_02 () {JPanel panel=NewJPanel (); JButton button1=NewJButton ("button One"); JButton Button2=NewJButton ("button Two");          Panel.add (button1);          Panel.add (button2);  This. Getcontentpane (). Add (panel);  This. setvisible (true); Button1.addactionlistener (NewActionListener () { Public voidactionperformed (ActionEvent e) {System.out.println ("You pressed the button one.");          }                  }); Button2.addactionlistener (NewActionListener () { Public voidactionperformed (ActionEvent e) {System.out.println ("You pressed the button two.");      }                  }); }       Public Static voidMain (String args[]) {Newtest_02 (); The use of anonymous inner classes to solve the problem of using if to get the source of the event is possible. But the use of anonymous inner classes also has some problems. Because it is in conjunction with the event group. Depending on the location of the event group in the code, the definition of the class and the handling of events are also not easy to read. If the event handler is complex, the code in the inner class becomes very long. Third, the use of general internal classes to achieve [Java] View plain copy Public classTest_03extendsjframe{test_03 () {JPanel panel=NewJPanel (); JButton button1=NewJButton ("button One"); JButton Button2=NewJButton ("button Two");          Panel.add (button1);          Panel.add (button2);  This. Getcontentpane (). Add (panel);  This. setvisible (true); Button1.addactionlistener (NewButton1actionlistener ()); Button2.addactionlistener (NewButton2actionlistener ()); }      Private classButton1actionlistenerImplementsactionlistener{ Public voidactionperformed (ActionEvent e) {System.out.println ("You pressed the button one."); }         }      Private classButton2actionlistenerImplementsactionlistener{ Public voidactionperformed (ActionEvent e) {System.out.println ("You pressed the button two."); }         }       Public Static voidMain (string[] args) {Newtest_03 (); }} We can solve a lot of problems with general internal classes, which avoids the confusion of code caused by the use of anonymous inner classes in the second method. It puts all the event handling methods together and has a meaningful name, and the program is very easy to read and maintain. Individual event handlers can also be reused by toolbars, menu bars, and so on. Based on the above summary, we generally use the third method to register events

Notes on the _java form program collation

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.