Java Interface Programming (4), java Interface Programming

Source: Internet
Author: User

Java Interface Programming (4), java Interface Programming

This article is my learning notes, welcome to reprint, but please note the Source: http://blog.csdn.net/jesson20121020

In the Swing event model, a component can initiate (trigger) an event. The types of each event are represented by different classes. When an event is triggered, it is received by one or more "listeners" and the listener is responsible for processing the event. Therefore, the place where an event occurs can be separated from the place where the event is handled. Since the Swing component is used in this way, you only need to write the code that will be called when the component receives the event. The event listener is an object that implements a listener interface of a specific type.

The following is an example of finding the addListener in the Swing component to demonstrate the Swing event model. The complete code is as follows:

Public class ShowAddListeners extends JFrame {private JTextField name = new JTextField (18); private JButton search = new JButton ("query"); private JTextArea results = new JTextArea (30,50 ); // define a regular expression to match addListenerprivate static Pattern addListener = Pattern. compile ("(add \ w +? Listener \\(.*? \) "); Private static Pattern qualifier = Pattern. compile ("\ w + \\. "); public ShowAddListeners () {setVisible (true); setSize (600,400); JPanel top = new JPanel (); top. add (new JLabel ("Swing Class name (press Enter):"); top. add (name); top. add (search); add (BorderLayout. NORTH, top); add (new JScrollPane (results); // The setting cannot be edited. // results. setEditable (false); search. addActionListener (new ActionListener () {@ Overridepublic voi D actionreceivmed (ActionEvent event) {// TODO Auto-generated method stub // remove the leading and trailing spaces of the keyword String nm = name. getText (). trim (); // if the length is after the keyword is removed, if (nm) is not matched successfully. length () = 0) {results. setText ("no match! "); Return;} Class <?> Kind; try {kind = Class. forName ("javax. swing. "+ nm);} catch (ClassNotFoundException e) {// TODO Auto-generated catch blockresults. setText ("no match! "); Return;} Method [] methods = kind. getMethods (); results. setText (""); for (Method m: methods) {Matcher matcher = addListener. matcher (m. toString (); // if a matching method is found, the if (matcher. find () {results. append (qualifier. matcher (matcher. group (1 )). replaceAll ("") + "\ n") ;}}}) ;}/ *** @ param args */public static void main (String [] args) {// TODO Auto-generated method stubnew ShowAddListeners ();}}
Effect:

The regular expression is used to match the listener. Here, only one listener is used to receive the listener. As mentioned above, the component can also bind multiple listeners.

The following describes several important event listeners for JButton, including FocusListener, KeyListener, MouseListener, and MouseMotionListener.
, Bind the buttons to these listeners. When the corresponding event occurs, the corresponding event is triggered to perform the corresponding operation. The complete code is as follows:

public class TrackEvent extends JFrame {private HashMap<String,JTextField> map = new HashMap<String,JTextField>();private String[] event = {"focusGained","focusLost","keyPressed","keyReleased","keyTyped","mouseClicked","mouseEntered","mouseExited","mousePressed","mouseReleased","mouseDragged","mouseMoved"};private MyButton b1 = new MyButton(Color.BLUE,"test1");private MyButton b2 = new MyButton(Color.RED,"test2");class MyButton extends JButton{private void report(String field,String msg){map.get(field).setText(msg);}private FocusListener fl = new FocusListener() {@Overridepublic void focusLost(FocusEvent e) {// TODO Auto-generated method stubreport("focusLost",e.paramString());}@Overridepublic void focusGained(FocusEvent e) {// TODO Auto-generated method stubreport("focusGained",e.paramString());}};private KeyListener kl = new KeyListener() {@Overridepublic void keyTyped(KeyEvent e) {// TODO Auto-generated method stubreport("keyTyped",e.paramString());}@Overridepublic void keyReleased(KeyEvent e) {// TODO Auto-generated method stubreport("keyReleased",e.paramString());}@Overridepublic void keyPressed(KeyEvent e) {// TODO Auto-generated method stubreport("keyPressed",e.paramString());}};private MouseListener ml = new MouseListener() {@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stubreport("mouseReleased",e.paramString());}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubreport("mousePressed",e.paramString());}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stubreport("mouseExited",e.paramString());}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stubreport("mouseEntered",e.paramString());}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stubreport("mouseClicked",e.paramString());}};private MouseMotionListener mml = new MouseMotionListener() {@Overridepublic void mouseMoved(MouseEvent e) {// TODO Auto-generated method stubreport("mouseMoved",e.paramString());}@Overridepublic void mouseDragged(MouseEvent e) {// TODO Auto-generated method stubreport("mouseDragged",e.paramString());}};public MyButton(Color color,String label) {super(label);setBackground(color);addFocusListener(fl);addKeyListener(kl);addMouseListener(ml);addMouseMotionListener(mml);}}public TrackEvent() {// TODO Auto-generated constructor stubsetLayout(new GridLayout(event.length + 1,2));for(String evt : event){JTextField tf = new JTextField();tf.setEditable(false);add(new JLabel(evt,JLabel.RIGHT));add(tf);setSize(700,500);setVisible(true);map.put(evt, tf);}add(b1);add(b2);}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubSwingUtilities.invokeLater(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubnew TrackEvent();}});}}
Execution result:


In this way, when you click, drag, or move an event, the corresponding listener is triggered to display the event action in the JTextField as a string, that is, the component tracks multiple events.





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.