Adapters vs anonymous inner class (please help)

I am trying to clean up my code by using anonymous inner classes to handle some action events. My code looks like this but I get an error
Button.addActionListener(new MyClass() {
public void actionPerformed(ActionEvent e) {
my_Button_actionPerformed(e);
it says that it cant find MyClass, but I thought I dont need to define it becaue I am defining it here, isnt that the point of a anonymous inner class

yourBtn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
});(BTW: use code tags in posting!)

Similar Messages

  • Question on Anonymous Inner class !

    Can an Anonymous Inner class implement or extend any thing?
    I feel no .. if yes can anyone give an example please..

    An example: the anonymous inner class in u extends Thread.
    $ cat u.java
    class u {
    public static void main(String a[]) {
    Thread t = new Thread ( ) {
    public void run() {
    System.out.println(getClass().getName());
    t.start();
    $ javac u.java
    $ java u
    u$1
    $
    The same idea but with the Runnable interface (and not class)
    $ cat u.java
    class u {
    public static void main(String a[]) {
    Thread t = new Thread ( new Runnable ( ) {
    public void run() {
    System.out.println(getClass().getName());
    t.start();
    $ java u
    u$1

  • Cant complie "anonymous inner class" on JDK1.4

    public Enumeration enumerator()
    return new Enumeration()
    int currentItem = items.size() - 1;
    public boolean hasMoreElements() {
    return (currentItem >= 0);
    error: cant resolve symbol
    help me! thanx u very much

    Since Enumeration is an interface, the anonymous inner class needs to implement both functions.
    public Enumeration enumerator()
      return new Enumeration()
         int currentItem = items.size() - 1;
         public boolean hasMoreElements()
            return (currentItem >= 0);
         public Object nextElement()
            return items.elementAt(currentItem--);
    }I assume that items is a member field of the class containing this method. Since I don't know what it is , the elementAt is only a guess.

  • Trying to use super class's methods from an anonymous inner class

    Hi all,
    I have one class with some methods, and a second class which inherits from the first. The second class contains a method which starts up a thread, which is an anonymous inner class. Inside this inner class, I want to call a method from my first class. How can I do this?
    If I just call the method, it will use the second class's version of the method. However, if I use "super," it will try to find that method in the Thread class (it's own super class) and complain.
    Any suggestions?
    Code:
    public class TopClass
         public void doSomething(){
              // do something
    =============================
    public class LowerClass extends TopClass
         // overrides TopClass's doSomething.
         public void doSomething(){
              // do something
         public void testThread(){
              Thread t = new Thread(){
                   public void run(){
                        doSomething();               //fine
                        super.doSomething();          //WRONG: searches class Thread for doSomething...
              t.start();
    }

    Classes frequently call the un-overridden versions of methods from their superclasses. That's that the super keyword is for, if I'm not mistaken.You're not mistaken about the keyword, but you're not calling the superclass method from a subclass. Your anonymous inner class is not a subtype of TopLevel. It's a subtype of Thread.
    Here it is no different, except that I happen to be in a thread at the time.It's vastly different, since you're attempting to call the method from an unrelated class; i.e., Thread.
    I could also be in a button's action listener, for example. It seems natural to me that if I can do it in a method, I should be able to do it within an anonymous inner class which is inside a method.If you were in an button's action listener and needed to call a superclass' implementation of a method overridden in the button, I'd have the same questions about your design. It seems smelly to me.
    ~

  • Semi-Anonymous Inner Class?

    From API description of invokeLater method of SwingUtilities class:
    /* begin quote
    In the following example the invokeLater call queues the Runnable object doHelloWorld on the event dispatching thread and then prints a message.
    Runnable doHelloWorld = new Runnable() {
    public void run() {
    System.out.println("Hello World on " + Thread.currentThread());
    SwingUtilities.invokeLater(doHelloWorld);
    System.out.println("This might well be displayed before the other message.");
    */ end quote
    The interface class is named (doHelloWorld) so it's not really anonymous.
    But the class is not declared; there's no class keyword.
    Is there a formal name for this construction?
    It seems like a hybrid of named and anonymous implementation.
    I guess the ability to mix class declaration, instantiation, method declaration, etc in one statement is powerful but just hard for beginner to understand when to use.
    Sigh, three ways to do same thing. This 'hybrid' form is actually harder to understand than other ways.
    private class myRunnable implements Runnable {
    public void run() {
    System.out.println("Hello World on " + Thread.currentThread());
    myRunnable doHelloWorld = new myRunnable();
    OR
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    System.out.println("Hello World on " + Thread.currentThread());
    Thanks,
    Stanley.

    The interface class is named (doHelloWorld) so it's
    not really anonymous. No. There's a variable that points to an instance of that class, and the variable is named doHelloWorld. The class is anonymous.
    Is there a formal name for this construction?Anonymous inner class.

  • Question about anonymous inner class??

    Is there any error occurs,If a class declear & implement two anonymous inner classes ??

    public class TryItAndSee {
        void m() {
            Runnable x = new Runnable(){
                public void run() {
                    System.out.println("?");
            Runnable y = new Runnable(){
                public void run() {
                    System.out.println("!");
    }

  • Mysterious anonymous inner class in switch block

    public class MysteryFile {
      public enum Elements {
        WIND, EARTH, FIRE, WATER
      Elements el;
      public MysteryFile(Elements el) {
        this.el = el;
      public void whatIsItLike() {
        switch (el) {
          case WIND: System.out.println("A bit chilly sometimes"); break;
          case EARTH: System.out.println("Gets hands dirty."); break;
          case FIRE: System.out.println("Hot! skin melt"); break;
          case WATER: System.out.println("Cool! clean hands"); break;
          default: System.out.println("Don't know"); break;
      public static void main(String[] args) {
        MysteryFile anElement = new MysteryFile(Elements.FIRE);
        anElement.whatIsItLike();
    }When compiled in Netbeans or in the command line, generates an unexpected MysteryFile$1.class file. If the entire switch block is commented out and recompiled, it does not get generated. Where does this anonymous inner class come from?

    The MysteryFile$1 class looks something like this (javac 1.6.0_02):
    class MysteryFile$1 {
      static final int[] $SwitchMap$MysteryFile$Elements;
      static {
          // the line number (debug info) of this static initializer
          // is "switch (el)" line in MysteryFile.java
          $SwitchMap$MysteryFile$Elements =
                  new int[MysteryFile$Elements.values().length ];
          try {
              $SwitchMap$MysteryFile$Elements[
                      MysteryFile$Elements.WIND.ordinal() ] = 1;
          } catch (NoSuchFieldError e) {
              // fix stack?
          // repeat with EARTH(2), FIRE(3) and WATER(4)
    }... and the actual switch statement in 'MysteryFile' looks like so:
      //switch (el) {
      switch(MysteryFile$1.$SwitchMap$MysteryFile$Elements[
              this.el.ordinal() ])
      case 1:  // WIND
          break;
      case 2:  // EARTH
          break;
      case 3:  // FIRE
          break;
      case 4:  // WATER
          break;
      default:  // ...
      }I suppose this is necessary because the compiler can't guarantee that the runtime enum-constant-to-ordinal mapping will be identical to that at compile time (the API docs say it depends on the declaration order in the source code, which I think may change without breaking binary compatibility).
    PS MysteryFile$Elements.values() is a synthetic method that returns all enumeration constants in a MysteryFile$Elements array. Found this old related thread: [http://forum.java.sun.com/thread.jspa?threadID=617315]

  • Anonymous Inner Class question

    How can I get "foof" to be echoed to the screen?
    class MyClass {
       void go() {
          Bar b = new Bar();
          b.doStuff(new Foo() {
             public void foof() {
                System.out.println("foof");
    interface Foo {
       void foof();
    class Bar {
       void doStuff(Foo f) {}
    public class TestWonder {
       public static void main (String... args) {
       new MyClass().go();
       //Why doesn't this print out "foof" to the screen? Nothing is echoed to the screen.
    }

    Sorry to be so thick, but I thought that the code did that already. Apparently it doesn't. In other words, how would the code invoke the override foof()? I should be clearer:
    I know if I change Bar's doStuff() to
    void doStuff(Foo f) {
    System.out.println("bar's dostuff");
    }then when go() is executed bar's dostuff will print out. But, what about the override in the anonymous inner class?
    Edited by: RonNYC2 on Feb 5, 2010 1:03 PM
    Edited by: RonNYC2 on Feb 5, 2010 1:05 PM

  • Pass an array of argument defined anonymous inner class

    Can someone plz tell me what is wrong with this code?How can I correct it?
    interface NotImplemented{
         public void disp();
    public class Anonymous{
         public void disp(NotImplemented[] ni){
              System.out.println(ni.length);
              ni[0].disp();
         public static void main(String args[]){
              Anonymous a=new Anonymous();
              a.disp(new NotImplemented[5]{
                   public void disp(){
                        System.out.println("Array of inner classes disp");
    }     

    This is what I wanted to do:
    interface NotImplemented{
         public void disp();
    public class Anonymous{
         public void disp(NotImplemented[] ni){
              System.out.println(ni.length);
              ni[0].disp();
              ni[1].disp();
         public static void main(String args[]){
              Anonymous a=new Anonymous();
              a.disp(new NotImplemented[]{
                        new NotImplemented(){
                             public void disp(){
                                  System.out.println("Inside first implementor of NotImplemented interface");
                        new NotImplemented(){
                             public void disp(){
                                  System.out.println("Inside second implementor of NotImplemented interface");
    Thanks for all your help...

  • Error in creating a process using runtime class - please help

    Hi,
    I am experimenting with the following piece of code. I tried to run it in one windows machine and it works fine. But i tried to run it in a different windows machine i get error in creating a process. The error is attached below the code. I don't understand why i couldn't create a process with the 'exec' command in the second machine. Can anyone please help?
    CODE:
    import java.io.*;
    class test{
    public static void main(String[] args){
    try{
    Runtime r = Runtime.getRuntime();
         Process p = null;
         p= r.exec("dir");
         BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
         System.out.println(br.readLine());
    catch(Exception e){e.printStackTrace();}
    ERROR (when run in the dos prompt):
    java.io.IOException: CreateProcess: dir error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:63)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:550)
    at java.lang.Runtime.exec(Runtime.java:416)
    at java.lang.Runtime.exec(Runtime.java:358)
    at java.lang.Runtime.exec(Runtime.java:322)
    at test.main(test.java:16)
    thanks,
    Divya

    As much as I understand from the readings in the forums, Runtime.exec can only run commands that are in files, not native commands.
    Hmm how do I explain that again?
    Here:
    Assuming a command is an executable program
    Under the Windows operating system, many new programmers stumble upon Runtime.exec() when trying to use it for nonexecutable commands like dir and copy. Subsequently, they run into Runtime.exec()'s third pitfall. Listing 4.4 demonstrates exactly that:
    Listing 4.4 BadExecWinDir.java
    import java.util.*;
    import java.io.*;
    public class BadExecWinDir
    public static void main(String args[])
    try
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("dir");
    InputStream stdin = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stdin);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    System.out.println("<OUTPUT>");
    while ( (line = br.readLine()) != null)
    System.out.println(line);
    System.out.println("</OUTPUT>");
    int exitVal = proc.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
    A run of BadExecWinDir produces:
    E:\classes\com\javaworld\jpitfalls\article2>java BadExecWinDir
    java.io.IOException: CreateProcess: dir error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Unknown Source)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at BadExecWinDir.main(BadExecWinDir.java:12)
    As stated earlier, the error value of 2 means "file not found," which, in this case, means that the executable named dir.exe could not be found. That's because the directory command is part of the Windows command interpreter and not a separate executable. To run the Windows command interpreter, execute either command.com or cmd.exe, depending on the Windows operating system you use. Listing 4.5 runs a copy of the Windows command interpreter and then executes the user-supplied command (e.g., dir).
    Taken from:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • Anonymous inner class

    Hello
    In the following piece of code:
    import static tools.Print.*;
    interface ForInner {
         void who();
         String toString();
    class ForInnerWithParameters {
         int i;
         String s;
         ForInnerWithParameters(int i) {
              this.i = i;
    class NackedClass {
         public ForInner inner() {
              return new ForInner() {
                   private int i;
                        print("Inside inner class!");
                        i = 10;
                   public int getI() {
                        return i;
                   public void who() {
                        print("It's me, inner!");
                   public String toString() {
                        return "Anonymous class";
         public ForInnerWithParameters innerWith(int i, final String s) {
              return new ForInnerWithParameters(i) {
                   {     print("i = "+i);
                        print(s);
                        super.s = s;
                   public String getS() {
                        return s;
         public static void main(String[] args) {
              NackedClass nc = new NackedClass();
              ForInner fi = nc.inner();
              fi.who();
              ForInnerWithParameters fiwp = nc.innerWith(91, "Hello");
              print(fiwp.i);
              print(fiwp.s);
    i would like to assign to the variable s (inside ForInnerWithParameters class) the value "Hello" passed as a parameter in the main ( ForInnerWithParameters fiwp = nc.innerWith(91, "Hello"); )
    The method innerWith(int i, final String s) is getting the values 91 and "Hello". Both, the parameter in the method and the parameter in the class are named s. How can I assign the value s ("Hello") to the parameter s inside the class? this.s = s or super.s = s doesn't work. The only solution I found is to change either the name of the parameter s inside the method or the name of the parameter s inside the class.
    I hope the question is clear enough!
    Thanks a lot!

    I would have expected this.s to work, providing you used it every time (including getS()).
    But, to be honest, why bother? It's just pointlessly confusing to use s as your method parameter.

  • BUG: Oracle Java Compiler bug with anonymous inner classes in constructor

    The following code compiles and runs just fine using 1.4.2_07, 1.5.0_07 and 1.6.0_beta2 when compiling and running from the command-line.
    It does not run when compiling from JDeveloper 10.1.3.36.73 (which uses the ojc.jar).
    When compiled from JDeveloper, the JRE (both the embedded one or the external 1.5.0_07 one) reports the following error:
    java.lang.VerifyError: (class: com/ids/arithmeticexpr/Scanner, method: <init> signature: (Ljava/io/Reader;)V) Expecting to find object/array on
    stack
    Here's the code:
    /** lexical analyzer for arithmetic expressions.
    Fixes the lookahead problem for TT_EOL.
    public class Scanner extends StreamTokenizer
    /** kludge: pushes an anonymous Reader which inserts
    a space after each newline.
    public Scanner( Reader r )
    super( new FilterReader( new BufferedReader( r ) )
    protected boolean addSpace; // kludge to add space after \n
    public int read() throws IOException
    int ch = addSpace ? ' ' : in.read();
    addSpace = ch == '\n';
    return ch;
    public static void main( String[] args )
    Scanner scanner = new Scanner( new StringReader("1+2") ); // !!!
    Removing the (implicit) reference to 'this' in the call to super() by passing an instance of a static inner class 'Kludge' instead of the anonymous subclass of FilterReader fixes the error. The code will then run even when compiled with ojc. There seems to be a bug in ojc concerning references to the partially constructed object (a bug which which is not present in the reference compilers.)
    -- Sebastian

    Thanks Sebastian, I filed a bug for OJC, and I'll look at the Javac bug. Either way, OJC should either give an error or create correct code.
    Keimpe Bronkhorst
    JDev Team

  • NewInstance from variable class(Please Help)

    I want to generate an object from xml
    example :
    <com.toto.titi.variable>
         <name>tata</name>
         <age>20</age>
    </com.toto.titi.variable>
    my java code :
    str = "com.toto.titi.variable" ;
    int idx0 = str.lastIndexOf(".");
    String testObj = str.substring(idx0+1);
    Class cls = Class.forName(str);
    o_ = (testObj)cls.newInstance(); //testObj it's variable, i dont now origin class or Interface
    this code is not work
    Please help
    Thanks

    do a search on here for "beanbox"....that shows how to do object persistence and creation using xml.

  • JWindow class please help me

    sir<br>
    i design a splash window by the use of JWindow class
    i use the following constructor
    public class splash extends JWindow
    //get content pane and set by the setContentPane method
    and add the three panels in it.
    One JPanel have a JTextField
    but JTextField is not accept the input or focus
    means i try to write text in it but it not work
    the code as follows
    //Create Jwindow
    import javax.swing.*;
    import java.awt.*;
    public class SplashScreen extends JWindow
    public static void main(String args[])
    new SplashScreen().setVisible(true);
    //define Variables
    Toolkit tk=Toolkit.getDefaultToolkit();
    Container cp=getContentPane();
    SplashScreenPanel1 p1;
    SplashScreenPanel2 p2;
    SplashScreenPanel3 p3;
    SplashScreen()
    Dimension d=tk.getScreenSize();
    p1=new SplashScreenPanel1(d.getWidth(),d.getHeight());
    p2=new SplashScreenPanel2(d.getWidth(),d.getHeight());
    p3=new SplashScreenPanel3(d.getWidth(),d.getHeight());
    this.setSize(d);
    this.setContentPane(cp);
    this.getContentPane().setLayout(null);
    cp.setBackground(new Color(47,168,122));
    p1.setBounds(new Rectangle(0,(int)(d.getHeight()-100),(int)d.getWidth(),100));
    p2.setBounds(new Rectangle(0,0,(int)d.getWidth(),100));
    p3.setBounds(new Rectangle(0,100,(int)(d.getWidth()),400));
    this.getContentPane().add(p1);
    this.getContentPane().add(p2);
    this.getContentPane().add(p3);
    p1.b1.requestFocus();
    }//end of spalshscreen
    create JPanel
    public class spashscreenpanel3 extends JPanel
    JTextField t=new JTextField();
    splashscreenpanel3
    this.setSize(200,100);
    this.setLayout(null);
    t.setBounds(10,20,100,20);
    this.add(t);
    }//end of JPanel
    Please help me i am very thankful to u

    Some helpful information is here:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html
    import javax.swing.*;
    import java.awt.*;
    public class hamad extends JFrame
      public static void main(String args[]) 
        new hamad();
      //define Variables
      SplashScreenPanel1 p1;
      SplashScreenPanel2 p2;
      SplashScreenPanel3 p3;
      JWindow window;
      public hamad()
        createWindow(this);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(300,200);
        setLocation(500,300);
        setVisible(true);
      private void createWindow(JFrame frameReference) {
        window = new JWindow(frameReference);
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension d=tk.getScreenSize();
        p1=new SplashScreenPanel1();
        p2=new SplashScreenPanel2();
        p3=new SplashScreenPanel3();
        window.getContentPane().add(p1, "North");
        window.getContentPane().add(p2, "Center");
        window.getContentPane().add(p3, "South");
        window.setSize(d.width/4, d.width/4);
        window.setLocation(100,100);
        window.setVisible(true);
      private class SplashScreenPanel1 extends JPanel
        JTextField field;
        public SplashScreenPanel1()
          setBackground(new Color(200,150,190));
          setPreferredSize(new Dimension(100,50));
          field = new JTextField();
          field.setPreferredSize(new Dimension(100, 20));
          add(field);
      private class SplashScreenPanel2 extends JPanel
        JTextField field;
        public SplashScreenPanel2()
          setBackground(new Color(220,90,180));
          field = new JTextField();
          field.setPreferredSize(new Dimension(75,20));
          add(field);
      //create JPanel
      private class SplashScreenPanel3 extends JPanel
        JTextField t=new JTextField();
        public SplashScreenPanel3()
          setBackground(Color.pink);
          setPreferredSize(new Dimension(100,50));
          setLayout(null);
          t.setBounds(10,20,100,20);
          add(t);
      }//end of JPanel
    }//end of spalshscreen

  • HT1386 Trying to Sync - Unable to load data class - please help

    I just cleared my I-Pod Touch to put new music on it and my computer is prompting the following. "I-Tunes was unable to load data class information from sync sevices." Reconnect of try again later. Another prompt that keeps appearing is  "the application apple mobile device help quit unexpectedly." Please help me...

    Apple Mobile Device Restart. Disable all security software ex. Firewalls and Antivirus. Follow article http://support.apple.com/kb/TS1567  . The above listed article is correct by lllaass. I resolve it by unchecking the different categories in itunes sync pages... Plug in device, click on name on left side of itunes, Click on different sync pages like summary, info, music, movies, etc. You need to uncheck the main check box to sync content. An example would be unchecking "Sync Music" . You will then need to sync once for each category until you locate the source of your corrupt files or folders. Syncing without it checked removes content from device. Follow this step even if there is nothing on the device. Once you identify if it is picture or music etc. you will need to delete corrupt files or move them somewhere else on the computer so itunes can't find it anymore.

Maybe you are looking for

  • Connecting Yaskawa Sigma II Servo Drive (SGDH) to PCI-7344 and UMI-7774

    Hi, I have  NI PCI-7344 and UMI-7774 and i want to Connect the UMI-7774 to Yaskawa Sigma II Servo Drive (SGDH) , the servo motor drive is connected to the servo motor with original Yaskawa cables. 1.  do you know if National instruments provide speci

  • Changing sizes etc.

    Hi Guys Can someone tell me why Photoshop keeps changing settings for placing objects, image size etc.? For example: I create a new Photoshop document:      ppi: 300      Width: 160 mm      Heigth: 160 mm after clicking "OK", these go to 160,2 mm or

  • Forms - Getting sum of values in the lines field

    Hi I have a form which is not based on any table/view The user has some line level details and some header level details. on save/submit button it should be saved in different tables/columns Line level details: It has say two fields. Item and item co

  • Problems configuring Platform Domain with MS Sql Server

    Hi, We are having problems configuring a Platform Domain with MS Sql Server 2000. We are using Weblogic version 7.0.0.2. These are the steps we followed 1.We manually created a database called TestDB and created a user account called "system", pwd ==

  • Suitable external drive to use on my MBP with XDCAM EX?

    Can I use a FW400 drive with XDCAM EX on my MBP (2.4 GHz Intel Core 2 Duo 2 GB ram)? Or do I need a FW800. Or something else entirely? TY.