Java for the button to add listeners (event handling) four forms of summary __java

Source: Internet
Author: User
Tags event listener

      The following example program is to add three buttons to a panel, add three listener objects to act as a button, and when clicked on a different button, the background color of the panel is changed to the corresponding color:

Import java.awt.*;
Import java.awt.event.*;

Import javax.swing.*; public class buttonframe{public static void Main (string[] args) {    eventqueue.invokelater (()-&G T
        {        jframe frame= new creatbuttonframe ();
                frame.settitle ("Buttontest");
                frame.setdefaultcloseoperation (JFrame.EXIT_ON_CLOSE);	
	        frame.setvisible (TRUE);
	} class Creatbuttonframe extends jframe{private JPanel buttonpanel;
	private static final int default_width = 300;
	private static final int default_height = 200;
	    Public Creatbuttonframe () {setSize (default_width, default_height);
	    JButton Yellowbutton = new JButton ("Yellow");
	    JButton BlueButton = new JButton ("Blue");
	    JButton Redbutton = new JButton ("Red");
	    Buttonpanel = new JPanel (); Buttonpanel.add (Yellowbutton);
	    Buttonpanel.add (BlueButton);
	    Buttonpanel.add (Redbutton);
	    Add (Buttonpanel);
	    Coloraction yellowaction = new Coloraction (color.yellow);
	    Coloraction blueaction = new Coloraction (Color.Blue);
	    Coloraction redaction = new Coloraction (color.red);
	    Yellowbutton.addactionlistener (yellowaction);
	    Bluebutton.addactionlistener (blueaction);
	Redbutton.addactionlistener (redaction);
		Class Coloraction implements actionlistener{private Color backgroundcolor;
		Public coloraction (Color c) {backgroundcolor = C;
		public void actionperformed (ActionEvent event) {buttonpanel.setbackground (backgroundcolor); }
	}
}

      The above procedures do not have to define a class separately for the event listener and construct 3 objects of the class, so you can use a lambda expression to simplify the following:

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class buttonframe{public static void Main (string[] args) {Eventqueue.invokelater (()-> {JFrame frame=
        New Creatbuttonframe ();
        Frame.settitle ("Buttontest");
        Frame.setdefaultcloseoperation (Jframe.exit_on_close);	
	Frame.setvisible (TRUE);
	} class Creatbuttonframe extends jframe{private JPanel buttonpanel;
	private static final int default_width = 300;
	private static final int default_height = 200;
		Public Creatbuttonframe () {setSize (default_width, default_height);
		Buttonpanel = new JPanel ();
		Makebutton ("Yellow", color.yellow);
		Makebutton ("Blue", Color.Blue);
		Makebutton ("Red", color.red);
	Add (Buttonpanel);
	    public void Makebutton (String name, Color backgroundcolor) {JButton button = new JButton (name);
	    Buttonpanel.add (button);
	Button.addactionlistener (Event-> Buttonpanel.setbackground (backgroundcolor)); }
}

      In addition, when we are not accustomed to using lambda expressions, we prefer to create an event source container that implements the ActionListener interface, and then the container sets itself as a listener, you can modify it to the following form:

Import java.awt.*;
Import java.awt.event.*;

Import javax.swing.*; public class buttonframe{public static void Main (string[] args) {Eventqueue.invokelater (()-> {JFrame frame=
        New Creatbuttonframe ();
        Frame.settitle ("Buttontest");
        Frame.setdefaultcloseoperation (Jframe.exit_on_close);	
	Frame.setvisible (TRUE);
	} class Creatbuttonframe extends JFrame implements actionlistener{private JPanel Buttonpanel;
	private static final int default_width = 300;
	private static final int default_height = 200;
	Private Button Yellowbutton,bluebutton,redbutton;
		Public Creatbuttonframe () {setSize (default_width, default_height);
		Buttonpanel = new JPanel ();
		Yellowbutton=new button ("yellow");
		Bluebutton=new button ("Blue");
		Redbutton=new button ("Red");
		Yellowbutton.addactionlistener (this);
		Bluebutton.addactionlistener (this);
		Redbutton.addactionlistener (this);
		Buttonpanel.add (Yellowbutton);
		Buttonpanel.add (BlueButton); Buttonpanel.add (RedbuttON);
	Add (Buttonpanel);
		public void actionperformed (ActionEvent event) {Object source=event.getsource ();
		if (Source==yellowbutton) {buttonpanel.setbackground (color.yellow);
		}else if (Source==bluebutton) {buttonpanel.setbackground (Color.Blue);
		}else if (Source==redbutton) {buttonpanel.setbackground (color.red); }
	}
}

In addition, you can use a mechanism to specify the event listener, whose event handler contains a method call. For example, when a button listener needs to perform a call:

  Frame.domethod ();

You can create a listener from the EventHandler class:

  Eventhandler.create (Actionlistener.class,frame, "Domethod")

But using lambda expressions is easier:

  Event-> Frame.domethod ();

Therefore, this method of creating listeners through the EventHandler class is not commonly used. The complete example of the method is shown below, and the example prints "Hello World" after clicking the button "click here". "Message:

import java.awt.*; 
Import java.awt.event.*; 
Import javax.swing.*; 
Import java.beans.*; 
		public class Buttonhand extends jframe{public static void Main (String args[]) {JFrame frame = new Buttonhand (); 
		Frame.setsize (300, 400); 	
	Frame.setvisible (TRUE); 
		Public Buttonhand () {Super ("event handling"); 
		Setdefaultcloseoperation (Exit_on_close); 
		JButton button = new JButton ("click here"); 
		Container ContentPane = Getcontentpane (); 
		Contentpane.add (button, borderlayout.center); 
	Button.addactionlistener ((ActionListener) eventhandler.create (Actionlistener.class, this, "print");	
	public void print () {System.out.println ("Hello world!"); } 
}

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.