• 0

[Java] ActionListener.


Question

Hey, assuming that we have a class called GUI, inside it, there is a button called B1. What does it mean when you write the following: B1.addActionListener (new ActionListener() { ...... }); ... what does that mean? I know that addActionListener() takes an object as an argument, and the class should implement ActionListener, which means that if GUI is implementing ActionListener, then the method would be: B1.addActionListener(this); ...

However, I'm not being able to understand the "new ActionListener", is it an object? If yes, how are we able to create an object from an interface?

Link to comment
https://www.neowin.net/forum/topic/522349-java-actionlistener/
Share on other sites

11 answers to this question

Recommended Posts

  • 0
  Phr34Ck said:

Hey, assuming that we have a class called GUI, inside it, there is a button called B1. What does it mean when you write the following: B1.addActionListener (new ActionListener() { ...... }); ... what does that mean? I know that addActionListener() takes an object as an argument, and the class should implement ActionListener, which means that if GUI is implementing ActionListener, then the method would be: B1.addActionListener(this); ...

However, I'm not being able to understand the "new ActionListener", is it an object? If yes, how are we able to create an object from an interface?

It's an example of something called an "anonymous inner class" (which you can look up for full details).

Briefly:

new Thing(){//methods etc here}

creates a new instance of a new un-named class that extends/implements Thing

So what you're doing is creating a a new instance of an anonymous class that implements ActionListener.

The definition of the class (especially the actionPerformed method required by ActionListener) follows in the { ..... }.

This is the preferred way to create ActionListeners. If you use your GUI class as the ActionListener then you can have only one actionPerformed method - in which case its messy with mutliple buttons etc.

James

  • 0
  Phr34Ck said:

I was thinking about it, and it's the same thing with Exception handling. You throw a new Exception the way you want it, and then you handle it later, like when we use: throw new Exception() ... are they the same logic ?

Not really. new Exception() just creates a new instance of Exception.

With an anonymous inner class you are simultaneously defining and instantiating a brand new class.

add(new Thing() { .... methods etc});

is like a shorthand for

class MyThing extends Thing { .... methods etc}

add(new MyThing());

  • 0

It is important for you to know why you are creating an inner class. Inner classes are often used to create event handlers because the scope of the listener should be limited.

When you create a button, it's just a button. You can click on it, but if there is nothing "listening" to the click, nothing will happen to the button. You need to create an event handler to listen for that button click and then do something. First you must define an event listener class:

//inner class, you put this in another class to limit its scope.
class doStuff implements ActionListener{

public void actionPerformed(ActionEvent event){
 //You have to include this method, as defined by the ActionListener interface.
//Here, the stuff you want done when the event is "fired" goes here.
}
}

Next you must register the actionlistener to the respective component, be it a button, field, etc.

myComponent.addActionListener(new doStuff());

If you want to create the ActionListener object, then register it to the component, that is fine.

ActionListener handler = new doStuff();
myComponent.addActionListener(handler);

  • 0

I do appreciate your reply Unholy Moley!, but that does not help me. I already know that, my question was about the myComponent.addActionListener (new ActionListerner() { .... }); that bit only. I'm not understanding what does that mean. What's happening there? I normally use the way you described, but I want to understand this way as well.

  • 0
  Phr34Ck said:

my question was about the myComponent.addActionListener (new ActionListerner() { .... }); that bit only. I'm not understanding what does that mean. What's happening there?

Oh, I understand your question now. To be honest, I've never seen that before either. It doesn't make much sense to me. Do you have a sample java file containing that code that can be compiled?

  • 0
  Phr34Ck said:

Here's a quick example

public class GUI extends JFrame
{
	private JButton B1;

	public GUI ()
	{
		 B1 = new JButton ("blabla");
		 B1.addActionListener ( new ActionListener() {
										  public void actionPerformed (ActionEvent e)
										  { //stuff here } }
										);
	 }
}

Feels like I'm talking to myself here.

It's an anonymous inner class.

It's an anonymous inner class - remember Google anyone?

It defines a new class that implements ActionListener and, at the same time, creates a new instance of that class. The new instance is then added as the ActionListener for B1. All in one go.

It's the same as Unholy Moley's example, except that the class is defined in the same statement as where the instance is created and passed to addActionListener, so it doesn't need to have a name.

This web site explains it in rather cutesy language, if the official language definition is too heavy going. http://www.javaranch.com/campfire/StoryInner.jsp

James

  • 0

Ahhh, your second post was everything I need. I makes sense now, so it created an innerclass directly that implements ActionListener, sweet.

Is it a good thing? If we had like 10 buttons in our class, and we used this method, we would be end up having 10 inner classes, yes? is it better then having only actionPerformed () in the class to handle the buttons?

  • 0
  Phr34Ck said:

Ahhh, your second post was everything I need. I makes sense now, so it created an innerclass directly that implements ActionListener, sweet.

Is it a good thing? If we had like 10 buttons in our class, and we used this method, we would be end up having 10 inner classes, yes? is it better then having only actionPerformed () in the class to handle the buttons?

Good question! If you have just one actionPerformed() it's going to need to test which Button generated the Event in some horrid n-way if test (or a cunningly-created switch). I guess most people would rather have a separate method for each button, defined right there where it's added to the Button, rather than have all the code for all the buttons all mixed up in one big method. That's certainly the official Sun Java position. Think about what happens when you wan to add or remove Buttons, or, best of all, re-use a Button somewhere else! The whole reason for the anonymous inner class construct is that it allowes you to have the 10 classes with a minimum of code overhead.

10 classes or one big method - the choice is yours!

J

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Movavi Video Editor Plus 25.12.0 by Razvan Serea With Movavi Video Editor, you can either enhance your video files with two or three simple steps, or turn them into something completely new. Create your own movies using multiple filters, transitions, and special effects: show multiple videos on one screen with the Picture in picture effect or change the background with the Chroma Key effect, imitate the camera zoom or make your video look like an old-style movie. Adjust video parameters such as brightness, contrast and colors. Stabilize shaky footage, improve video quality and remove defects. Create video presentations, tutorials or educational videos: add titles and record your own narration to create a video with voiceover. Import video from any source: TV-tuner, webcam, camcorder, or VHS. Drop multiple media files onto a timeline and let your imagination do the rest! Features at a glance: Video and audio editing on a timeline Edit, enhance videos Add background music Apply titles and effects Image quality improvement Hollywood-worthy effects High-grade titles and fades Digitize VHS tapes, record video from TV tuners Stabilize any shaky sections Support for a wide range of formats Prepare your videos for uploading to YouTube, Facebook, Vimeo, or any other website New in Movavi Video Editor 2025: Revamped timeline for easier editing The new timeline is now clearer and more streamlined. Get your projects done faster and have more fun with anything – from short vids for socials to longer family movies. Frame-precise cuts in a click Give your videos a sharper look with the new Blade tool. Easily make precise cuts and create eye-catching montages like your favorite bloggers. Pro-quality color correction Get next-level color correction with the same simplicity. Boost colors in a snap and make more viewers fall in love with your videos. AI motion tracking Enhance reality in your videos with additional moving graphics. Just click, and AI will quickly attach any photos, videos, emojis, or memes to objects in your footage. Perfect-match overlay effects Now each overlay effect has 13 blending modes to choose from. Try each of them with the press of a button and pick the one that fits your video perfectly. Best video effects – at your fingertips Create awesome videos in any style with our huge collection of professionally designed effects. Now you can try them all right away, right in the app. Movavi Video Editor 25.12.0 changelog: Just a minor upgrade to keep everything running smoothly. Download: Movavi Video Editor Plus 25.12.0 | 5.1 MB (Shareware) View: Movavi Video Editor Plus Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Major Privacy 0.98.3 Beta by Razvan Serea MajorPrivacy is a cutting-edge privacy and security tool for Windows, offering unparalleled control over process behavior, file access, and network communication. It is a continuation of the PrivateWin10 project. By leveraging advanced kernel-level protections, MajorPrivacy creates a secure environment where user data and system integrity are fully safeguarded. Unlike traditional tools, MajorPrivacy introduces innovative protection methods that ensure mounted encrypted volumes are only accessible by authorized applications, making it the first and only encryption solution of its kind. MajorPrivacy – Ultimate Privacy & Security for Windows key features Process Protection – Isolate processes to block interference from unauthorized apps, even with admin privileges. Software Restriction – Block unwanted apps and DLLs to ensure only trusted software runs. Revolutionary Encrypted Volumes Secure Storage – Create encrypted disk images for sensitive data. Exclusive Access – Unlike traditional tools, only authorized apps can access mounted volumes—blocking all unauthorized processes. File & Folder Protection – Lock down sensitive files and prevent unauthorized access or modifications. Advanced Network Firewall – Control which apps can send or receive data online. DNS Monitoring & Filtering – Track domain access and block unwanted sites (Pi-hole compatible filtering coming soon). Tweak Engine – Disable telemetry, cloud integration, and invasive Windows features for better privacy. Why MajorPrivacy? Kernel-Level Security – Protects at the deepest system level. Unmatched Encryption Protection – Keeps mounted volumes safe from all unauthorized access. Full System Control – Block, isolate, or restrict processes as needed. Enhanced Privacy – Stops Windows & apps from collecting unnecessary data. Perfect for privacy-conscious users, IT pros, and anyone who wants total system control. Major Privacy 0.98.3 Beta changelog: This release of MajorPrivacy introduces several important improvements, bug fixes, and optimizations. The resource access rules engine has been enhanced to include the user as an additional parameter, enabling finer-grained access control. CPU usage has been reduced in both the user interface and background service, improving overall performance. The ImBox feature has been updated to avoid modifying container file timestamps when accessing secure encrypted volumes. Firewall rule handling has been improved for Store Apps on Windows 23H2 and later versions, increasing compatibility and reliability. A critical issue has been resolved in ImBox.exe that affects the mounting of older encrypted volumes; users should use a previous build to recover data and then recreate the volumes using this or a later version. Additionally, several interface and functionality bugs have been addressed: translations now load correctly, the Data Editor’s tree view now functions properly across multiple .dat files, and the Execution Monitor displays entries as expected when a time filter is applied. The “Add to Group” menu now correctly lists all available groups, and folder creation is no longer incorrectly permitted under Directory Listing and Read-only actions. Download: Major Privacy 0.98.3 Beta | 59.4 MB (Open Source) View: MajorPrivacy Home Page | Github Project page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Hi there! Great question and yes, the Twenty Twenty-Four theme (TT4) + Gutenberg does have a few quirks when it comes to spacing and columns. To reduce the spacing between the image and the text in a two-column layout, here are a few things to try:  1. Adjust Block Spacing (Direct Method) Click on the Column Block (the outer wrapper that holds both your image and text). In the right sidebar, under "Block" > "Dimensions", look for the "Block spacing" setting (sometimes called “Gap”). Reduce the value (in px, em, or %) to tighten the space between elements inside that column. 2. Use Padding & Margin Controls Click on the Image block, and then the Text block individually. Under “Dimensions”, adjust the Margin of the Image or Text block (especially bottom or top margin) to reduce extra white space. Try setting margins to 0 or a small number like 8px. 3. Use Group Block (Optional) If the spacing controls aren’t behaving: Wrap the image + text inside a Group block. Then apply padding/margin settings to the inner blocks for better control.
    • Looks interesting, I love the art style. How many people are working on the game?
  • Recent Achievements

    • Reacting Well
      water01 earned a badge
      Reacting Well
    • First Post
      Aidan Helfrich earned a badge
      First Post
    • Collaborator
      bullgod69 earned a badge
      Collaborator
    • Enthusiast
      Ed B went up a rank
      Enthusiast
    • Reacting Well
      Xinotema earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      764
    2. 2
      ATLien_0
      187
    3. 3
      +FloatingFatMan
      151
    4. 4
      Xenon
      118
    5. 5
      wakjak
      113
  • Tell a friend

    Love Neowin? Tell a friend!