ActionListener as nested class, anonymous class etc.

I'm programing my own text editor and im trying to decide in what way to implement an ActionListener for JMenuItems.
I've got 3 possible ideas of how to implement it.
First way is to implement the ActionListener in the same class as the JMenu and use a switch statement or a fairly long if-else statement.
Second way is to create nested classes for each ActoinEvent.
public class OuterClass {
     //Some random code here...
     private class ActionClass implements ActionListener{
          public void actionPerformed(ActionEvent e) {
               //Random code.
}And final way is creating anonymous classes adding ActionListeners for each JMenuItem.
menuItem.addActionListener(new AbstractAction(){
public void actionPerformed(ActionEvent e) {
});But i can't decide on wich of these are the moste correct and accepted way.
Could someone point me to the right direction?
Edited by: Idono on Jun 3, 2010 7:36 PM

the only time you would do the first one would be if you wanted several ActionListeners to do the EXACT SAME THING.
Then you just write the "actionClass" one time, and have each Component use it.
private class ActionClass implements ActionListener{
          public void actionPerformed(ActionEvent e) {
               //Random code.
menuItem.addActionListener(new ActionClass());
menuItem1.addActionListener(new ActionClass());
menuItem2.addActionListener(new ActionClass());
menuItem3.addActionListener(new ActionClass());But (as the other person mentioned) usually you use anonymous classes because each component has different actions.
menuItem.addActionListener(new AbstractAction(){
public void actionPerformed(ActionEvent e) { ... }
menuItem1.addActionListener(new AbstractAction(){
public void actionPerformed(ActionEvent e) { ... }
menuItem2.addActionListener(new AbstractAction(){
public void actionPerformed(ActionEvent e) { ... }
});

Similar Messages

  • JDWP reference implementation does not return anonymous nested classes?

    Using
    $ java -version
    java version "1.6.0_22"
    Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
    Java HotSpot(TM) Client VM (build 17.1-b03, mixed mode, sharing)
    it appears that when I connect with JDWP and issue a NestedTypes command, the result does not include anonymous nested types. The only references to this that I could find is a comment in a svn commit at apache (http://mail-archives.apache.org/mod_mbox/harmony-commits/200611.mbox/%[email protected]%3E)
    Is this intentional and desired? Is there a way to get all of the nested types, including the anonymous ones? I could do ClassesBySignature with "package.ClassName$*" as the signature and filter out doubly nested classes, but that seems overly complicated.

    exept, you can NOT have an implementation of an
    abstract class (which foundPlugin) is without an
    implementation of all it's subclasses (such as
    argsObject) You're mistaken in a couple of ways here.
    First, a nested class is not the same as a subclass.
    Second, a concrete class must have implementations for all its methods, but it can still have an abstract nested class.
    Third, you can have an instance of a concrete class that has abstract subclasses. Object is concrete and has many concrete subclasses. Classes don't know anything about their subclasses.
    This compiles.
    public abstract class AbOut {
      public abstract class AbIn {  public abstract void bar(); }
    public class ConcOut extends AbOut {
      public abstract class AbIn2 { public abstract void foo();}
    foundPlugin MUST have an implementation
    of argsObject, according to the rules of java,And you think this because...?
    You read it in the JLS? Citation please.
    You tried to compile and it failed? My sample above demonstrates the countereample. If I'm misunderstanding what you're talking about, please post an example
    Or maybe you just thought it had to be that way because that seemed the most intuitive and when it wasn't, rather than trying to understand or adjust your thinking, you figured it would be more fun to throw a hissy fit and call Java "stupid"?

  • Question about nested classes

    Hi, i currently have the following problem:
    I have 2 classes, one of which also has a nested class:
    1. Home.java (extends JApplet)
    2. Away.java (extends JPanel) has nested class, private class ButtonListener implements ActionListener
    Now in Home.java I have a Vector ( called bankaccount) which i pass to the Constructor of Away.java ( I declared the vector again there as an instance by Private Vector bankaccount;).
    My problem is that in ButtonListener I am trying to access the Vector so that i can modify it when a button has been clicked, and i thought i could just use the commands of bankaccount.add() and bankaccount.get() directly, however it seems like ButtonListener cannot access the Vector, even though i passed it along to the Constructor of the Away class.
    Any suggestions on how i get access the Vector from the ButtonListenere class?

    This is an example:
    public class Home extends JApplet
    private Away away;
    private Vector bankaccount;
    public void init()
         bankaccount = new Vector();
         away = new Away(bankaccount);
    public class Away extends JPanel
    private Vector bankaccount;
    JTextArea text1= new JTextArea(50,50);
    public Away(Vector bankaccount)
       //declare buttons,textarea,setLayout,etc
    button1.addActionListener (new ButtonListener());
    //i can set  text1.setText(( String)bankaccount.get(0));
    // here to access bankaccount, and it shows up fine, but i want
    // do it in from the class below
    private class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event)
                         //trying to access bankaccount here by doing:
                        // but it is not doing anything
                        text1.setText(( String)bankaccount.get(0));
    }

  • Questions concerning Nested Classes

    Hi!
    Just read some articles about nested classes (include the ones from the Java Tutorial and the Effective Java chapter), and while most of it is perfectly clear, three questions remain:
    1.) When I declare a member class, how should I declare the access specifiers (private, protected etc.) for the member class's attributes and methods? If I declare a member class as private, anything but private for the attributes and methods wouldn't make sense, would it?
    2.) The Java Tutorial says:
    Also, because an inner class is associated with an instance, it cannot define any static members itself.While this is true for static methods, it seems to be possible to declare static variables inside inner classes. This is confusing me... does it actually make sense to declare static variables inside inner classes (or member classes in general)? Or should the be placed in the declaring class?
    3.) Another confusing quote from the Java Tutorial:
    Static nested classes do not have access to other members of the enclosing class.This is true for instance variables and methods but not for static variables, which are also members of the enclosing class, aren't they?
    Thanks in advance,
    OIiver

    Trollhorn wrote:
    Hi!
    Just read some articles about nested classes (include the ones from the Java Tutorial and the Effective Java chapter), and while most of it is perfectly clear, three questions remain:
    1.) When I declare a member class, how should I declare the access specifiers (private, protected etc.) for the member class's attributes and methods? If I declare a member class as private, anything but private for the attributes and methods wouldn't make sense, would it?
        private static class MyInner implements Runnable
            @Override public void run() // Must be public!
    2.) The Java Tutorial says:
    Also, because an inner class is associated with an instance, it cannot define any static members itself.While this is true for static methods, it seems to be possible to declare static variables inside inner classes. This is confusing me... does it actually make sense to declare static variables inside inner classes (or member classes in general)? Or should the be placed in the declaring class?Wrong. It can define static final member variables and I see no reason to move them to the outer class, if they are used only by the inner class.
    3.) Another confusing quote from the Java Tutorial:
    Static nested classes do not have access to other members of the enclosing class.This is true for instance variables and methods but not for static variables, which are also members of the enclosing class, aren't they?I agree with you here.
    Edited by: baftos on Jun 6, 2009 9:18 AM

  • When to use Nested Class/Inner Classes ?

    I am not very clear, when to use nested/inner classes..
    The scenario is :-
    class ABC
    //ABC need to store multiple instance of class XYZ
    class XYZ
    int member1;
    int member2;
    One approach is
    class ABC
    class XYZ
    //vector of class XYZ instances is stored in class-ABC
    or another approach is Class XYZ can be in separate JAVA file.
    Query:-
    1) Is there any difference between nested or Inner class...or are they same?
    2) When should they be used....Is it good to use in above scenario.
    3) What are the disadvtanges/advantages of using the Nested
    class.

    Query:-
    1) Is there any difference between nested or Inner
    class...or are they same?I really don't get it. Yes there is a difference between having an inner class, and a class in a separate file, but a nested class is an inner class.
    2) When should they be used....Is it good to use in
    above scenario.To write an inner class is a design decision. Do other classes need to know about the class XYZ or not? Do the XYZ class need to know about the inner working of the ABC class? How complex is the XYZ class etc.
    >
    3) What are the disadvtanges/advantages of using the
    Nested
    class.See above.
    /Kaj

  • Implementing ActionListener in inner class

    Hi
    I'm trying to add an action listener to a button. When i add the new actionlistener i create an anonymous non static inner class at the same time, which has a actionPerfomed(ActionEvent e) method. My checkString() method is in another package, Validate, which i have imported.
    When i try to run the program, i get the following error message:
    GUI/MyGraphics.java [74:1] non-static method checkString(java.lang.String) cannot be referenced from a static context
    boolean textOk = Validator.checkString(userInput);
    ^
    The problem is do with the face that the compiler sees actionPerfomed(ActionEvent e) as a static method/context. How is it static?
    (when i preview my code, it loses all it's indentation. how can i fix this?)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import Interfaces.*;
    import Validate.*;
    public class MyGraphics
        public void startGui()
            JFrame f = new JFrame("Greetings!");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container c = f.getContentPane();
            JLabel lblTop = new JLabel("Who are you? Please enter your                             .       name...");
            c.add(lblTop, BorderLayout.NORTH);
            final JLabel lblResponse = new JLabel();
            c.add(lblResponse, BorderLayout.SOUTH);
            final JLabel lblResponse2 = new JLabel();
            c.add(lblResponse2, BorderLayout.EAST);
            final TextField tfOne = new TextField("My name is...", 50);
            c.add(tfOne, BorderLayout.CENTER);
            JPanel jp = new JPanel();
            JButton Bok = new JButton("Ok");
            jp.add(Bok);
            JButton Bbye = new JButton("Bye!");
            jp.add(Bbye);
            c.add(jp, BorderLayout.SOUTH);
            f.pack();
            f.show();  
            Bok.addActionListener(new ActionListener(){    
            public void actionPerformed(ActionEvent e)
                try
                    String userInput = tfOne.getText();
                    boolean textOk = Validator.checkString(userInput);
                        if(textOk == true)
                            lblResponse.setText("You Have Success!");
                        else
                            lblResponse.setText("Sorry, No Success.");
                catch (Exception a)
                    lblResponse.setText("ERROR! You must enter a valid   value");
    }

    thank you, that is exactly what i needed.
    also, i don't know how to keep my code indentation. i type it in the text field with proper indents but when i preview it, it loses all formatting. how can i prevent this happening?

  • Extending inner [nested] classes

    OK I've got a class (A) with a nested class (B).
    B accesses variables etc. in A and does its own thing, but what I'd like to do is make B abstract and have a number of classes extend it - which is used depends on program arguments.
    The problem I'm having is that the new class (C) that extends B does not seem to have access to any of the variables in A.
    I originally tried:
    class C extends B
    and
    class C extends A$B
    I also tried this, which I found on this site:
    class C extends A.B
    (thats A-dot-B) but it still doesnt seem to be working.
    Is it possible to extend [abstract] inner classes like this? If so, how? Any help appreciated. cheers.

    Here I found a solution. However, it is not so elegant. In fact, I am also having trouble in extending a nested class in an elegant way.
    Here, A is the original top-level class and A.B is the nested class of A. A2 extends A. B2 and B3 extends A.B. Main is the class where the main() method can be found.
    // A.java
    public class A {
      private B b;
      public void setB (B b) {
        this.b = b;
      public B getB () {
        return b;
      public abstract class B {
        public abstract String getName();
    // A2.java
    public class A2 extends A {
      public class B2 extends A.B {
        public String getName () {
          return "Peter";
      public class B3 extends A.B {
        public String getName () {
          return "John";
    public class Main {
      public static void main (String[] args) {
        A a = new A2 ();
        A.B b = ((A2)a).new B2 ();
        a.setB (b);
        System.out.println (a.getB().getName());  // John
        b = ((A2)a).new B3 ();
        a.setB (b);
        System.out.println (a.getB().getName());  // Peter
    }You may see here that I used "A" as the type of "a". Te reason is I want to use "a" as an "A", not "A2". If you don't want to do casting, you may simply use "A2" as the type. The class A2 can be blank. It is only a "container" of the classes B2 and B3.

  • Cloning nested classes

    Does anyone know where I can get information on how
    clone() behaves with nested classes? thanks ...

    I'm actually talking about nested classes (such
    as inner classes), not objects as iv's. Can I assume that an inner class's
    native iv's get a shallow copy as well? I can think of a number of ambiguous
    situations and am wondering if these issues are discussed anywhere, if there
    are any general cautions, etc? Maybe there is nothing to this but on the
    face of it it seems complex.

  • Nameless Nested Classes passed in Function Parameter?

    I am trying to get my head around the following code example:
    javax.swing.SwingUtilities.invokeLater( new Runnable() { public void run() { createAndShowGUI(); }});What is actually getting passed to the SwingUtilities.invokeLater() function?
    Can anyone explain all of the parts and pieces of :
    new Runnable() { public void run() { createAndShowGUI(); }} ?
    Here is my best guess:
    1) { public void run() { createAndShowGUI(); }} is an unnamed nested class that is instantiated using the Runnable() interface.
    2) this class has one method called run() that executes createAndShowGUI();
    Is my best guess even close to what is really going on?

    richard.broersma wrote:
    1) { public void run() { createAndShowGUI(); }} is an unnamed nested class that is instantiated using the Runnable() interface.Yes, that's essentially correct. It's called an anonymous inner class.
    This is similar to doing
    // a non-anonymous inner class
    private class MyClass implements Runnable
      public void run()
        createAndShowGUI();
    MyClass myclass = new MyClass();
    javax.swing.SwingUtilities.invokeLater(myclass);
    2) this class has one method called run() that executes createAndShowGUI();Yes. It must have a parameterless public void run method since it implements the Runnable interface.
    Is my best guess even close to what is really going on?Yes, you're catching on.

  • Why a nested class can instantiate an abstract class?

    Hi people!
    I'm studying for a SCJP 6, and i encountered this question that i can figure it out but i don't find any official information of my guess.
    I have the following code:
    public class W7TESTOQ2 {
        public static void main(String[] args) {
           // dodo dodo1 = new dodo();
            dodo dodo2 =new dodo(){public String get(){return "filan";}};
            dodo.brain b = dodo2.new brain(){public String get(){return "stored ";}};
            System.out.print(dodo2.get()+" ");
            System.out.println(b.get());
    abstract class dodo
        public String get()
            return "poll";
        abstract class brain
            public abstract String get();
    }I know that abstract classes cannot be instantiated but i see that in this example, with a nested anonymous class it does (dodo and brain classes). My guess is that declaring the nested class it makes a subclass of the abstract class and doing so it can be instantiated. But i can't find any documentation about this.
    Does anybody know?
    Really thanks in advance.
    Regards,
    Christian Vielma

    cvielma wrote:
    Another question about this. Why can't i declare a constructor in the nested class? (it gives me return type required)You cannot declare a constructor, because in one line you're declaring a new class (the anonymous inner class) as well as constructing an instance of it.
    What you can do, however, is if the abstract class (or the superclass, in any case, it doesn't need to be abstract) defines several constructors, you can call them.
    public abstract MyClass {
        public MyClass() {
            // Default do nothing constructor
        public MyClass(String s) {
            // Another constructor
    // Elsewhere
    MyClass myclass = new MyClass("Calling the string constructor") {
    };But you can't define your own constructors in the anonymous inner class.
    Also, since the class is anonymous, what would you name the constructor? :)
    Edited by: Kayaman on 26.6.2010 22:37

  • Static nested class

    Hi there.
    Im playing around with static nested classes:
    class OuterC {
         int x = 10;
         static class Nest {
              void doStuff() {
                   System.out.println("Going");
                   //System.out.println("Should be allowed print: " + x);
                   doOtherStuff();
              public void doOtherStuff() {
                   System.out.println("Doing Stuff!");
    public class Test {
         static class OtherNest {
              void arbitraryMethod() {
                   System.out.println("Going to do arbitrary stuff...");
         public static void main(String[] args) {
              OuterC.Nest n = new OuterC.Nest();
              n.doStuff();
              OtherNest on = new OtherNest();
              on.arbitraryMethod();
    }//close TestWhen I uncomment the statement to print out the instance variable x of class OuterC
    I get a "cannot access non-static..." error, which is fine. I expect that.
    But why can I run the doOtherStuff() method from the static nested class Nest?
    doOtherStuff() is after all an instance method...
    Many Thanks & regards!
    Edited by: Boeing-737 on May 29, 2008 10:27 AM
    Dont bother replying, I see the error now. The method is defined as a member within the nested
    class. Apologies, I didn't spot that. My mistake.
    Thanks.
    Edited by: Boeing-737 on May 29, 2008 10:28 AM

    From the JLS, chapter 8:
    A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.
    This chapter discusses the common semantics of all classes-top level (?7.6) and nested (including member classes (?8.5, ?9.5), local classes (?14.3) and anonymous classes (?15.9.5)).
    So "nested" iff "not top level".From the JLS, chapter 8:
    An inner class is a nested class that is not explicitly or implicitly declared static.
    So a "static" nested class is a bit redundant, since a "non-static" nested class -- a nested class is either static or it isn't -- is more specifically referred to as an "inner class". That's my story and I'm sticking to it. :o)
    ~

  • Static nested class VS non-static nested class ??

    we know static method can be called without creating an object and static variables are shared among objects.
    what is the difference between static nested class and non-static nested class ? When do we use them? what is the advantages of static nested class over non-static nested class in term of performance?

    From the JLS, chapter 8:
    A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.
    This chapter discusses the common semantics of all classes-top level (?7.6) and nested (including member classes (?8.5, ?9.5), local classes (?14.3) and anonymous classes (?15.9.5)).
    So "nested" iff "not top level".From the JLS, chapter 8:
    An inner class is a nested class that is not explicitly or implicitly declared static.
    So a "static" nested class is a bit redundant, since a "non-static" nested class -- a nested class is either static or it isn't -- is more specifically referred to as an "inner class". That's my story and I'm sticking to it. :o)
    ~

  • How to override a nested class?

    I'm relatively new to Java, so this may be an easy question, but how do you override the behaviour of a nested class when extending a parent class? For example:
    public class MyParentClass
      public class MyParentNestedClass
        public void someMethod()
          // Some functionality that I want to change 
    }Now I want to create a new class, let's call it MyChildClass, which extends MyParentClass and changes the behaviour of the inner class. Is this possible? What is the syntax to accomplish this? Are there any scope-related problems I should be aware of?
    Do I have to extend the parent class in order to redefine the nested class, or is there some way to just override the nested class (which is all I really want to change)? Any help on this would be appreciated, I've searched both the Sun site and Google and can't come up with a really clear answer to this one.
    Thanks,
    Steve

    That's exactly what I was after. I was trying to do it like this:
    public class MyChildClass extends MyParentClass
      MyParentNestedClass childNestedClass = new MyParentNestedClass()
        public void someMethod() { /* new functionality */ }
    }because I have seen anonymous classes (I think they're called adapter classes) declared like this, but it wasn't working in this case. Thanks for showing me the correct way to do it, I guess in retrospect that makes perfect sense, I don't know why I didn't think of it.
    Thanks,
    Steve

  • Question about the property of the nested class.

    "Nested classes may be declared static. In this case, the nested class has no reference to an enclosing instance"
    Can any one demonstrate the above through an code example?? thanks

    thanks jverd.
    Then why dont you answer my other thread??You have several threads. I've said what I have tosay in all the ones that I know about, am interested
    in, and have the time to answer. Last one I lookedat, you were in Monica's very capable hands, so I had
    nothing to add.
    Thanks!I may not be the sharpest knife in the drawer, but I know better than to piss of her what's gonna administer the dread Blueberry Pie Torture.

  • Flex RPC mapping Java nested classes to ActionScript classes

    We are calling a Java method in our project using
    RemoteObject the value returned by the java method is a ArrayList
    containing instances of a class say ParentClass with some nested
    classes.
    The structure of ParentClass(Java) is something like this
    class ParentClass {
    //some primitives
    private ChildClassA childAInstance;
    private ChildClassB childBInstance;
    //getters setters
    We have created similar class structure on the ActionScript
    side, the ActionScript classes(ParentClass,ChildClassA
    ,ChildClassB) have been properly annotated with the [RemoteClass]
    metadata tag,
    The problem is that though i'm getting the primitive data
    members of the ParentClass through RPC in my corresponding AS
    ParentClass class i'm getting an runtime exception trying to access
    ChildClassA,ChildClassB members.
    Am i missing something, exactly the same scenario is
    mentioned in this article
    http://www.adobe.com/devnet/flex/articles/complex_data.html
    But the Object.registerClass method mentioned in the tutorial
    is giving me compilation error, the sample code attached with the
    article is corrupt zip too.
    Please help me out on this

    JAXB will create classes from an XML schema, SAX is a parser library and JAXP is a library of XML a bunch of XML tools.
    I don't care for JAXB too much. I would skip it and go right to the JAX-RPC spec (WebServices).

Maybe you are looking for

  • Accounting entries process in Fixed Asset Module

    Dear all, I don't know Accounting entries process in Fixed Asset Module. I don't know how to post accounting entries and manage fixed assets Anyone can share me documents that is relevant to business transaction in  fixed asset module. My ID: [email 

  • Hooking cable to tv

    I have recently bought 2 tv's for in 2 different rooms.  I just got cable hooked up in each room and now I have the tv's both hooked up.  The problem is that the tv upstairs works fine and gets all the cable channels, while the tv downstairs in the l

  • Tax reports for Israel

    I am busy with an full FICO implementation for one of our business units in Israel and need information on country specific tax reporting programs! Are there country specific programs for Israel that generate a DME file for the tax autorities? Frank

  • ABAP: error generating the test frame

    Hi ABAP gurus, I received below error during execute/test the function module. Could anyone help or advice me why i'm getting the below error. Error generating the test frame Message no. FL819 Diagnosis The system could not generate a syntactically c

  • Server Farm Help in 2010

    If I had a 2 server (Central Admin & WFE) would it be reasonable for the following to be true; CA to have sharepoint foundation web application turned ON, and the other WFE server have it turned OFF CA to have sharepoint foundation incoming email tur