[java] Please explain this Java code to me.

Started by
2 comments, last by Lord_Evil 15 years, 3 months ago
I am trying to learn Java right now and the only time I’ve ever used it was in a small intro course at a community college a few years ago. I am experimenting with NetBeans right now and it generated the following code:
  

        jButtonAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddActionPerformed(evt);
            }
        });

What exactly is going on here? Is it looks like it is creating a temporary derived class and overriding the constructor and the actionPerformed function. Is that what is going on? Also, is there an easy way I can run non applet Java programs without having to use the Command Prompt or the IDE?
-----------------------------Download my real time 3D RPG.
Advertisement
Quote:
What exactly is going on here?


It is creating a new ActionListener object, and overriding the actionPerformed method, then passing the newly created object to the addActionListener method. The other option would be to simply create an entire new class extending the ActionListener object and overriding the actionPerformed method, then creating a new instance of the object to pass to addActionListener. However, if you used this method with several different buttons, you would need to create separate classes for each one, which would create more unnecessary code and clutter.
In case you were wondering what it's technically called, it's an anonymous class. Feel free to google the term for several more articles on it.
[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]
Quote:Original post by ManaStone
Also, is there an easy way I can run non applet Java programs without having to use the Command Prompt or the IDE?


Assuming you mean desktop applications:

1. Make a batch file (.bat or .sh) containing the command (either java <class> or java -jar <jarfile>
2. Make an executable jar, which at least on windows can be executed on double click (if you assigned 'java.exe' to the '.jar' extension).

The same is true for command line applications, but you wouldn't get the output. ;)

For other application types (JEE components, Midlets, Servlets, ...) there are other ways. ;)
If I was helpful, feel free to rate me up ;)If I wasn't and you feel to rate me down, please let me know why!

This topic is closed to new replies.

Advertisement