A little summary of developing a swing feature

Source: Internet
Author: User

For the JTextField, there are two ways to perform the validation:
(1) Use Javax.swing.InputVerifier to verify when the focus is acquired
(2) Check the value of the control in the listen event of the "OK" button

Given the number of businesses involved, the code structure has been determined, and if it is performed in the "OK" button's listening event, a step is needed, and not all businesses need this validation,
tend to use javax.swing.InputVerifier, there are two benefits, (1) Separation of business logic and front-end (2) code more elegant

Javax.swing.InputVerifier used a few, and then found that the control features and the previous UE difference:
"The validator is not a problem and it is safe. If a button is clicked, and the button notifies its action listener before the invalid member gets the focus again, the action listener will not get an invalid result from the validation widget. The reason for this behavior is that the user may want to click the Cancel button without correcting the invalid input "

Another problem is that if the control JTextField does not have the focus in Java.awt.Container, the correlation check will not work

(Abstract) Java.awt.FocusTraversalPolicy Adjust Focus order (not in effect)
or increase monitoring on Container , after Container executes Setvisile (TRUE)
Addwindowfocuslistener (New Windowadapter () {
public void Windowgainedfocus (WindowEvent e) {
Textfield.requestfocusinwindow ();
}
});

After such processing, there are some unexpected anomalies on the Win7 program, and the process logic of the program is increased because of increased monitoring, and the structure is adjusted.

In view of the above, the Constraintcheck logic is eventually added to the processing flow in the "OK" button's listener


A sample on the tutorials:

 Packagemisc;Importjava.awt.*;Importjava.awt.event.*;ImportJava.util.Vector;Importjavax.swing.*;/** Focustraversaldemo.java requires no other files.*/ Public classFocustraversaldemoextendsJPanelImplementsActionListener {StaticJFrame frame;    JLabel label;    Jcheckbox Togglepolicy; StaticMyownfocustraversalpolicy Newpolicy;  PublicFocustraversaldemo () {Super(NewBorderLayout ()); JTextField TF1=NewJTextField ("Field 1"); JTextField TF2=NewJTextField ("A bigger Field 2"); JTextField TF3=NewJTextField ("Field 3"); JTextField Tf4=NewJTextField ("A bigger Field 4"); JTextField Tf5=NewJTextField ("Field 5"); JTextField TF6=NewJTextField ("A bigger Field 6"); JTable Table=NewJTable (4,3); Togglepolicy=NewJcheckbox ("Custom focustraversalpolicy"); Togglepolicy.setactioncommand ("Toggle"); Togglepolicy.addactionlistener ( This); Togglepolicy.setfocusable (false);//Remove it from the focus cycle. //Note that HTML is allowed and would break this run of text//across, lines.Label =NewJLabel ("); JPanel Lefttextpanel=NewJPanel (NewGridLayout (3,2));        Lefttextpanel.add (TF1, Borderlayout.page_start);        Lefttextpanel.add (TF3, Borderlayout.center);        Lefttextpanel.add (Tf5, borderlayout.page_end); Lefttextpanel.setborder (Borderfactory.createemptyborder (0,0,5,5)); JPanel Righttextpanel=NewJPanel (NewGridLayout (3,2));        Righttextpanel.add (TF2, Borderlayout.page_start);        Righttextpanel.add (TF4, Borderlayout.center);        Righttextpanel.add (TF6, borderlayout.page_end); Righttextpanel.setborder (Borderfactory.createemptyborder (0,0,5,5)); JPanel Tablepanel=NewJPanel (NewGridLayout (0,1));        Tablepanel.add (table, borderlayout.center);        Tablepanel.setborder (Borderfactory.createetchedborder ()); JPanel Bottompanel=NewJPanel (NewGridLayout (2,1));        Bottompanel.add (Togglepolicy, Borderlayout.page_start);        Bottompanel.add (label, Borderlayout.page_end);        Add (Lefttextpanel, Borderlayout.line_start);        Add (Righttextpanel, borderlayout.center);        Add (Tablepanel, borderlayout.line_end);        Add (Bottompanel, borderlayout.page_end); SetBorder (Borderfactory.createemptyborder (20,20,20,20)); Vector<Component> order =NewVector<component> (7);        Order.add (TF1);        Order.add (TF2);        Order.add (TF3);        Order.add (TF4);        Order.add (TF5);        Order.add (TF6);        Order.add (table); Newpolicy=NewMyownfocustraversalpolicy (order); }    //Turn The custom focus traversal policy on/off,//according to the checkbox     Public voidactionperformed (ActionEvent e) {if("Toggle". Equals (E.getactioncommand ())) {Frame.setfocustraversalpolicy (togglepolicy.isselected ()?Newpolicy:NULL); }    }    /*** Create The GUI and show it.     For thread safety, * This method should is invoked from the * event-dispatching thread. */    Private Static voidCreateandshowgui () {//Create and set up the window.frame =NewJFrame ("Focustraversaldemo");        Frame.setdefaultcloseoperation (Jframe.exit_on_close); //Create and set up the content pane.JComponent Newcontentpane =NewFocustraversaldemo (); Newcontentpane.setopaque (true);//content panes must be opaqueFrame.setcontentpane (Newcontentpane); //Display the window.Frame.pack (); Frame.setvisible (true); }     Public Static voidMain (string[] args) {/*Use a appropriate look and feel*/        Try {            //Uimanager.setlookandfeel ("Com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); //Uimanager.setlookandfeel ("Com.sun.java.swing.plaf.gtk.GTKLookAndFeel");Uimanager.setlookandfeel ("Javax.swing.plaf.metal.MetalLookAndFeel"); } Catch(Unsupportedlookandfeelexception ex) {ex.printstacktrace (); } Catch(Illegalaccessexception ex) {ex.printstacktrace (); } Catch(Instantiationexception ex) {ex.printstacktrace (); } Catch(ClassNotFoundException ex) {ex.printstacktrace (); }        /*Turn off Metal ' s use of bold fonts*/Uimanager.put ("Swing.boldmetal", Boolean.false); //Schedule a job for the event-dispatching thread://creating and showing this application ' s GUI.Javax.swing.SwingUtilities.invokeLater (NewRunnable () { Public voidrun () {Createandshowgui ();    }        }); }     Public Static classMyownfocustraversalpolicyextendsFocustraversalpolicy {Vector<Component>order;  PublicMyownfocustraversalpolicy (vector<component>order) {             This. Order =NewVector<component>(Order.size ());  This. Order.addall (order); }         PublicComponent getcomponentafter (Container focuscycleroot, Component acomponent) {            intIDX = (Order.indexof (acomponent) + 1)%order.size (); returnorder.get (IDX); }         PublicComponent Getcomponentbefore (Container focuscycleroot, Component Acomponen T) {intIDX = Order.indexof (acomponent)-1; if(IDX < 0) {idx= Order.size ()-1; }            returnorder.get (IDX); }         PublicComponent getdefaultcomponent (Container focuscycleroot) {returnOrder.get (0); }         PublicComponent getlastcomponent (Container focuscycleroot) {returnorder.lastelement (); }         PublicComponent getfirstcomponent (Container focuscycleroot) {returnOrder.get (0); }    }}



Public abstract class Inputverifier extends Object
The purpose of this class is to help clients support smooth focus navigation through a GUI with text fields. Before allowing the user to navigate to a text field, such a GUI often needs to ensure that the text entered by the user is valid (for example, the text has the correct format). To do this, the client uses the JComponent Setinputverifier method to create a subclass of Inputverifier and attaches an instance of its subclass to the jcomponent to validate its input. The Shouldyieldfocus method of the input validator is called before the focus is transferred to another Swing component that requests it. Only the focus is shifted when the method returns True.

The following example has two text fields, where the first field expects the user to enter a string of "pass". If you enter the string in the first text field, the user can advance to the second text field by clicking on the second Text field or pressing TAB. However, if you enter a different string into the first text field, the user cannot transfer the focus to the second text field.

Importjava.awt.*; ImportJava.util.*; Importjava.awt.event.*; Importjavax.swing.*; //This program demonstrates the use of the Swing Inputverifier class.//It creates text fields, the first of the text fields expects the//string "Pass" as input, and would allow the focus to advance out of it//Only after this string is typed in by the user.  Public classVerifiertestextendsJFrame { Publicverifiertest () {JTextField TF1=NewJTextField ("Type \" Pass\ "Here");           Getcontentpane (). Add (TF1, Borderlayout.north); Tf1.setinputverifier (Newpassverifier ()); JTextField TF2=NewJTextField ("TextField2");            Getcontentpane (). Add (TF2, Borderlayout.south); WindowListener L=NewWindowadapter () { Public voidwindowclosing (windowevent e) {system.exit (0);           }           };     Addwindowlistener (l); }      classPassverifierextendsInputverifier { Public BooleanVerify (JComponent input) {JTextField tf=(JTextField) input; return"Pass". Equals (Tf.gettext ()); }     }       Public Static voidMain (string[] args) {Frame F=Newverifiertest ();           F.pack (); F.setvisible (true); } }







A little summary of developing a swing feature

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.