Accessing method in an inner class

I have a class, which has an Inner Class, which is an extension of AbstractTableModel. The extended TableModel class has a new method, so it looks something like this;
public class TheOuterClass
    JTable aTable
    TableModel theTableModel
    public initTable
         theTableModel = new MyTableModel();
     public TableModel getModel()
         return theTableModel;
     private class MyTableModel extends AbstractTableModel
            public void myTableModelMethod()
}So, the idea here is that I have a class that has a table referenced by 'aTable', which uses MyTableModel as the class for it's table model. I have only implemented the basics here. The class also has a method called getModel(), so from a reference to 'TheOuterClass', I can access the table model.
Now, say I have a reference to TheOuterClass called toc, and I want to access my new method in the table model;
toc.getModel().myTableModelMethod()The above won't work, because getModel() returns a type of TableModel.
My question then is how do I cast this to the correct type, so I can access the method 'myTableMethod()'?
Is for example, the following a legal possibility, because I cannot seem to make it work;
(toc.getModel().getClass())(toc.getModel()).myTableMethod();The quick fix, I guess is to correct getModel in TheOuterClass, so it returns the correct type, but I am hoping to not do this. (This is part of a larger piece of code obviously, and TheOuterClass is in reality a bean, and I don't wnat to disturb anymore than I have to).
Any suggestions / ideas would be gratefully appreciated

You are of course both correct, the class is private, should have spotted that! Doh. Also correct in that this is 'not the most elegant design', but you know the way it is you have to work with what you are given.
So, I changed the class to public....
What I had hoped is that the following would work
((toc.getModel().getClass())(toc.getModel())).myTableMethod()get a reference to the table model
(toc.getModel())cast it to the correct type (not sure if this is a valid way to cast??)
((toc.getModel().getClass())(toc.getModel()))then call the method.
This does not compile, it complains about a missing ')', and I'm sure they are all there. My question here then is, Is this a valid way to cast, now that the inner class is public?
As to why I want to do this, then some explanation is required;
The table model holds a Vector with all the data in it, some which is not actually in the table (it was originally written this way). My additional method myTableMethod() is intended to help access the data that is not shown in the table.
Coming back to kajbj's point of creating an interface, I presume what is being suggested is that I create a public interface with the myTableMethod() in it, and make myTableModel implement this interface. Since the interface is public, then I can cast to that. Is this what you meant?
Thanks for your help so far

Similar Messages

  • How to access private method of an inner class using reflection.

    Can somebody tell me that how can i access private method of an inner class using reflection.
    There is a scenario like
    class A
    class B
    private fun() {
    now i want to use method fun() of an inner class inside third class i.e "class c".
    Can i use reflection in someway to access this private method fun() in class c.

    I suppose for unit tests, there could be cases when you need to access private methods that you don't want your real code to access.
    Reflection with inner classes can be tricky. I tried getting the constructor, but it kept failing until I saw that even though the default constructor is a no-arg, for inner classes that aren't static, apparently the constructor for the inner class itself takes an instance of the outer class as a param.
    So here's what it looks like:
            //list of inner classes, if any
            Class[] classlist = A.class.getDeclaredClasses();
            A outer = new A();
            try {
                for (int i =0; i < classlist.length; i++){
                    if (! classlist.getSimpleName().equals("B")){
    //skip other classes
    continue;
    //this is what I mention above.
    Constructor constr = classlist[i].getDeclaredConstructor(A.class);
    constr.setAccessible(true);
    Object inner = constr.newInstance(outer);
    Method meth = classlist[i].getDeclaredMethod("testMethod");
    meth.setAccessible(true);
    //the actual method call
    meth.invoke(inner);
    } catch (Exception e) {
    throw new RuntimeException(e);
    Good luck, and if you find yourself relying on this too much, it might mean a code redesign.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to override a method in an inner class of the super class

    I have a rather horribly written class, which I need to adapt. I could simply do this if I could override a method in one of it's inner classes. My plan then was to extend the original class, and override the method in question. But here I am struggling.
    The code below is representative of my situation.
    public class ClassA
       ValueChecks vc = null;
       /** Creates a new instance of Main */
       public ClassA()
          System.out.println("ClassA Constructor");
          vc = new ValueChecks();
          vc.checkMaximum();
         // I want this to call the overridden method, but it does not, it seems to call
         // the method in this class. probably because vc belongs to this class
          this.vc.checkMinimum();
          this.myMethod();
       protected void myMethod()
          System.out.println("myMethod(SUPER)");
       protected class ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUPER)");
             return true;
          protected boolean checkMaximum()
             return false;
    }I have extended ClassA, call it ClassASub, and it is this Class which I instantiate. The constructor in ClassASub obviously calls the constructor in ClassA. I want to override the checkMinimum() method in ValueChecks, but the above code always calls the method in ClassA. The ClassASub code looks like this
    public class ClassASub extends ClassA
       public ClassAInner cias;
       /** Creates a new instance of Main */
       public ClassASub()
          System.out.println("ClassASub Constructor");
       protected void myMethod()
          System.out.println("myMethod(SUB)");
       protected class ValueChecks extends ClassA.ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUB)");
             return true;
    }The method myMethod seems to be suitably overridden, but I cannot override the checkMinimum() method.
    I think this is a stupid problem to do with how the ValueChecks class is instantiated. I think I need to create an instance of ValueChecks in ClassASub, and pass a reference to it into ClassA. But this will upset the way ClassA works. Could somebody enlighten me please.

    vc = new ValueChecks();vc is a ValueChecks object. No matter whether you subclass ValueChecks or not, vc is always of this type, per this line of code.
    // I want this to call the overridden method, but it does not, it seems to > call
    // the method in this class. probably because vc belongs to this class
    this.vc.checkMinimum();No, it's because again vc references a ValueChecks object, because it was created as such.
    And when I say ValueChecks, I mean the original class, not the one you tried to create by the same name, attempting to override the original.

  • Re: [SunONE-JATO] How to Access methods in the MainAppServletBase class from a view bean

    OK, fair enough.
    Look at the ServletConfig class.
    c
    Purvashada wrote:
    >
    We had that option. We decided against the
    property files as we can get this dynamically.
    There has been problems when this property
    was set incorrectly at the time of installation.
    Are there any api's to get the servername and
    port number other than through request object..
    --- "Craig V. Conover" <craig.conover@s...> wrote:
    So I guess my question is, why do you need a user
    request to get this
    information?
    You should be able to get this info when the
    application is started up,
    from a props file.
    Does this info change from day to day? If not, why
    not create a props
    file on the machine that the app is running that has
    this info?
    Then in the servlet's init method, read this prop
    file.
    Does that work for you? Not sure how a user request
    is needed to
    determine this? If it is, please explain.
    I have used this same technique for database
    properties (servername,
    instance name, uid, pwd, etc).
    On the QA machine was the properties that pointed to
    the QA database,
    and on the Production machine, the property file
    with the same name had
    props that pointed to the Production database.
    craig
    Purvashada wrote:
    It is a static data that is same for all theusers.
    It is application level data but generateddynamically
    to get the server name and the port number the appis
    running on..
    Thanks
    --- "Craig V. Conover" <craig.conover@s...>wrote:
    OK, so how does doing this only once help you.
    Wouldn't you need to do
    this for each individual end user?
    I'm not suggesting that this is request scoped,but
    maybe session scoped.
    If so, then do this in the module servlet's
    onNewSession event.
    If this is per user, then storing it staticallyis
    problematic because
    all users will be using the same data which Idon't
    think you want.
    Let me know if my assumptions are correct.
    craig
    Purvashada wrote:
    Basically, I need to pass the host url/request
    url
    to
    another server which then posts the results
    back to this server.
    I need to get the host url dynamically.
    This is what I am doing in my code to
    get the host url..
    URL =req.getScheme() + "://" +
    req.getServerName()
    +
    ":" + req.getServerPort();
    Thanks
    --- "Craig V. Conover" <craig.conover@s...>wrote:
    Correct, that is a per request event.
    Sounds like we need to figure out a newapproach.
    Please elaborate on your requirements for
    doing
    whatever it is you require.
    Maybe we can suggest an alternative, orperhaps
    reveal that it may not
    be necessary after all.
    craig
    Purvashada wrote:
    I had added this code in the
    initializeRequestContext(..)
    Hoping it would be called once.
    It looks like it is called for every
    request.
    HttpServletRequest req =requestContext.getRequest();
    setActionURL(req);
    If I add the code in the init() method
    how can I get the HttpServletRequest
    getRequest()
    Thanks
    --- "Craig V. Conover"
    <craig.conover@s...>
    wrote:
    cool.
    Be careful about how you update this URL
    when
    you
    use setURL method.
    The servlets in JATO are the only shared
    (Application scope rather than
    Request scope like ViewBeans and
    Models),
    and
    that
    you could potentially
    have sync/multithread issues. You said
    you
    were
    only
    updating once at
    the start of the App, so you should be
    fine.
    I
    assume you are doing this
    from an init method or init event in theservlet
    class? If so, no worries.
    Also, just to be sure everyone follows,
    I am
    not
    suggesting that you
    write syncronize code in the servlets asthis
    will
    be a potential bottle
    neck in your app's scalibility. This is
    not
    a
    JATO
    shortcoming as there
    are alternatives to do this sort of
    coding.
    craig
    Purvashada wrote:
    I made the method static and is
    accessible..
    --- "Craig V. Conover"<craig.conover@s...>
    wrote:
    I would assume it is a static
    method, so
    just
    do:
    MainAppServletBase.getURL()
    right?
    If not static, it probably should
    be. If
    you
    feel it
    should not be
    static, let us know why/what your
    requirements
    are.
    >
    === message truncated ===
    To download the latest version of S1AF (JATO), please visit one of the
    following locations:
    Framework + IDE plugin for Sun ONE Studio 4 Update 1, Community Edition:
    http://wwws.sun.com/software/download/products/Appl_Frmwk_2.0_CE.html
    Framework + IDE pluign for Sun ONE Studio 4 Update 1, Enterprise Edition:
    http://wwws.sun.com/software/download/products/Appl_Frmwk_2.0_EE.html
    Previous versions of JATO:
    http://www.sun.com/software/download/developer/5102.html

    OK, fair enough.
    Look at the ServletConfig class.
    c
    Purvashada wrote:
    >
    We had that option. We decided against the
    property files as we can get this dynamically.
    There has been problems when this property
    was set incorrectly at the time of installation.
    Are there any api's to get the servername and
    port number other than through request object..
    --- "Craig V. Conover" <craig.conover@s...> wrote:
    So I guess my question is, why do you need a user
    request to get this
    information?
    You should be able to get this info when the
    application is started up,
    from a props file.
    Does this info change from day to day? If not, why
    not create a props
    file on the machine that the app is running that has
    this info?
    Then in the servlet's init method, read this prop
    file.
    Does that work for you? Not sure how a user request
    is needed to
    determine this? If it is, please explain.
    I have used this same technique for database
    properties (servername,
    instance name, uid, pwd, etc).
    On the QA machine was the properties that pointed to
    the QA database,
    and on the Production machine, the property file
    with the same name had
    props that pointed to the Production database.
    craig
    Purvashada wrote:
    It is a static data that is same for all theusers.
    It is application level data but generateddynamically
    to get the server name and the port number the appis
    running on..
    Thanks
    --- "Craig V. Conover" <craig.conover@s...>wrote:
    OK, so how does doing this only once help you.
    Wouldn't you need to do
    this for each individual end user?
    I'm not suggesting that this is request scoped,but
    maybe session scoped.
    If so, then do this in the module servlet's
    onNewSession event.
    If this is per user, then storing it staticallyis
    problematic because
    all users will be using the same data which Idon't
    think you want.
    Let me know if my assumptions are correct.
    craig
    Purvashada wrote:
    Basically, I need to pass the host url/request
    url
    to
    another server which then posts the results
    back to this server.
    I need to get the host url dynamically.
    This is what I am doing in my code to
    get the host url..
    URL =req.getScheme() + "://" +
    req.getServerName()
    +
    ":" + req.getServerPort();
    Thanks
    --- "Craig V. Conover" <craig.conover@s...>wrote:
    Correct, that is a per request event.
    Sounds like we need to figure out a newapproach.
    Please elaborate on your requirements for
    doing
    whatever it is you require.
    Maybe we can suggest an alternative, orperhaps
    reveal that it may not
    be necessary after all.
    craig
    Purvashada wrote:
    I had added this code in the
    initializeRequestContext(..)
    Hoping it would be called once.
    It looks like it is called for every
    request.
    HttpServletRequest req =requestContext.getRequest();
    setActionURL(req);
    If I add the code in the init() method
    how can I get the HttpServletRequest
    getRequest()
    Thanks
    --- "Craig V. Conover"
    <craig.conover@s...>
    wrote:
    cool.
    Be careful about how you update this URL
    when
    you
    use setURL method.
    The servlets in JATO are the only shared
    (Application scope rather than
    Request scope like ViewBeans and
    Models),
    and
    that
    you could potentially
    have sync/multithread issues. You said
    you
    were
    only
    updating once at
    the start of the App, so you should be
    fine.
    I
    assume you are doing this
    from an init method or init event in theservlet
    class? If so, no worries.
    Also, just to be sure everyone follows,
    I am
    not
    suggesting that you
    write syncronize code in the servlets asthis
    will
    be a potential bottle
    neck in your app's scalibility. This is
    not
    a
    JATO
    shortcoming as there
    are alternatives to do this sort of
    coding.
    craig
    Purvashada wrote:
    I made the method static and is
    accessible..
    --- "Craig V. Conover"<craig.conover@s...>
    wrote:
    I would assume it is a static
    method, so
    just
    do:
    MainAppServletBase.getURL()
    right?
    If not static, it probably should
    be. If
    you
    feel it
    should not be
    static, let us know why/what your
    requirements
    are.
    >
    === message truncated ===
    To download the latest version of S1AF (JATO), please visit one of the
    following locations:
    Framework + IDE plugin for Sun ONE Studio 4 Update 1, Community Edition:
    http://wwws.sun.com/software/download/products/Appl_Frmwk_2.0_CE.html
    Framework + IDE pluign for Sun ONE Studio 4 Update 1, Enterprise Edition:
    http://wwws.sun.com/software/download/products/Appl_Frmwk_2.0_EE.html
    Previous versions of JATO:
    http://www.sun.com/software/download/developer/5102.html

  • Accessing the inner class written inside the method

    Hi all,
    Can any of you tell me how to access the inner class's method which is written inisde the outer class's method. THe code fragment is
    class Outer
    private static final int ID = 3;
    public String name;
    public void methodA( int nn )
    final int serialN = 11;
    class inner
    void showResult()
    System.out.println( "Rslt= "+ID );
    } // end class inner
    // new inner().showResult();
    } // end methodA
    class Sample
    public static void main(String a[])
    //access the showResult of Inner class??
    Thanks in advance.
    aah

    class Outer {
      private static final int ID = 3;
      public String name;
      public void methodA( int nn ) {
        final int serialN = 11;
        class inner {
          void showResult() {
            System.out.println( "Rslt= "+ID );
        } // end class inner
        new inner().showResult();
      } // end methodA
    class Sample {
      public static void main(String a[]) {
        new Outer().methodA(5);
    }

  • Why we are making a variable as final in method inner class ?

    Why we are making the variable as final (method inner class) while we are accessing the method variable in inner class ?
    regards,
    namanc

    As far as I can tell, the only reason is to protect the programmer: when the inner class instance is constructed, it is given the then-current value of the variable. If the variable (or method parameter) later changes, the value held by the inner class would not. By making the variable final, the programmer doesn't have to worry about them staying in sync.
    Here's some code to ponder:
    public class InnerExample
        void printMe( final int x )
            Runnable runMe = new Runnable()
                public void run()
                    System.out.println(x);
            (new Thread(runMe)).start();
    }When compiled with the Sun JDK 1.4.2, you get this bytecode:
    void printMe(int);
      Code:
       0:   new     #2; //class InnerExample$1
       3:   dup
       4:   aload_0
       5:   iload_1
       6:   invokespecial   #3; //Method InnerExample$1."<init>":(LInnerExample;I)V
       9:   astore_2
       10:  new     #4; //class Thread
       13:  dup
       14:  aload_2
       15:  invokespecial   #5; //Method java/lang/Thread."<init>":(Ljava/lang/Runnable;)V
       18:  invokevirtual   #6; //Method java/lang/Thread.start:()V
       21:  returnAt line (byte) 5, it loads the passed value onto the stack; at line 6, it invokes the inner class constructor (which is created by the compiler). Nothing in this sequence of code would prevent use of a non-final variable.

  • How to access super of enclosing class from inner class?

    Hello,
    I'd like to access Base.foo() from inner class in overridden Improved.foo(), but seem unable:
    public class InnerSuper {
         public static class Base {
              protected int foo() {
                   return 1;
         public static class Improved extends Base {
              @Override
              protected int foo() {
                   return Integer.parseInt(new Object () {
                        public String toString() {
                             return "1"+foo() ;
                   }.toString());
         public static void main(String[] args) {
              System.out.println(new Improved().foo());
    }The code above does not work, as it recursively calls Improved.foo() where I'd like it to call Base.foo(). What syntax construct should I use? Improved.this would be the same thing, Improved.super does not exist.
    I came up with a work around: adding a method baseFoo() to Improved and call that in the inner class:
       int baseFoo() {
          return super.foo();
       } but remain wondering if that is necessary?

    Indeed, Improved.super.foo() is allowed. My Eclipse syntax highlighting seems to have the same opinion as you: "are you sure you want to write that kind of code?" and leaves the read underlining for a syntax error on for just a second longer.
    This is where I am now:
         public static class DeferredExecSubroutineCall extends SubroutineCall {
              RelayExecutor relay;
              public DeferredExecSubroutineCall(RelayExecutor relay) {
                   this.relay = relay;
              @Override
              protected String execute(final IFDSOC fd, final String commandText) {
                   Future<String> f = relay.submit(new Callable<String>() {
                        @Override
                        public String call() throws Exception {
                             return DeferredExecSubroutineCall.super.execute(fd, commandText);
                   try {
                        return f.get();
                   } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                   } catch (ExecutionException e) {
                        if (e.getCause() instanceof RuntimeException) {
                             throw (RuntimeException) e.getCause();
                        } else {
                             throw new RuntimeException(e.getCause());
         }which is my current effort of adding concurrency to an existing project. I find it quite elegant but I am interested to hear from you...

  • Method local Inner classes

    The local variables of the method live on the stack, and exist only for the lifetime of the method. You already know that the scope of a local variable is limited to the method the variable is declared in. When the method ends, the stack frame is blown away and the variable is history. But even after the method completes, the inner class object created within it might still be alive on the heap if, for example, a reference to it was passed into some other code and then stored in an instance variable. Because the local variables aren’t guaranteed to be alive as long as the method-local inner class object, the inner class object can’t use them. Unless the local variables are marked final! The following code attempts to access a local variable from within a method-local inner class.
    Can any one explaing me with an example of the above BOLDED text.

    Can any one explaing me with an example of the above BOLDED text
    class Outer {
         Outer outer;
         void method() {
              int i=0;
              class Local extends Outer {
                   int j = i;
              outer = new Local();
    }The above code doesn't compile unless the i variable in method() is declared final.

  • Main method not found and how to put event handlers in an inner class

    How would I put all the event handling methods in an inner class and I have another class that just that is just a main function, but when i try to run the project, it says main is not found. Here are the two classes, first one sets up everything and the second one is just main.
    mport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class JournalFrame extends JFrame {
    private JLabel dateLabel = new JLabel("Date: ");
    private JTextField dateField = new JTextField(20);
    private JPanel datePanel = new JPanel(new FlowLayout());
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel radioPanel = new JPanel();
    JPanel statusPanel = new JPanel();
    JPanel textAreaPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    GridLayout gridLayout1 = new GridLayout();
    FlowLayout flowLayout1 = new FlowLayout();
    GridLayout gridLayout2 = new GridLayout();
    GridLayout gridLayout3 = new GridLayout();
    JRadioButton personalButton = new JRadioButton();
    JRadioButton businessButton = new JRadioButton();
    JLabel status = new JLabel();
    JTextArea entryArea = new JTextArea();
    JButton clearButton = new JButton();
    JButton saveButton = new JButton();
    ButtonGroup entryType = new ButtonGroup();
    public JournalFrame(){
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void initWidgets(){
    private void jbInit() throws Exception {
    this.getContentPane().setLayout(borderLayout1);
    radioPanel.setLayout(gridLayout1);
    statusPanel.setLayout(flowLayout1);
    textAreaPanel.setLayout(gridLayout2);
    buttonPanel.setLayout(gridLayout3);
    personalButton.setSelected(true);
    personalButton.setText("Personal");
    personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
    businessButton.setText("Business");
    status.setText("");
    entryArea.setText("");
    entryArea.setColumns(10);
    entryArea.setLineWrap(true);
    entryArea.setRows(30);
    entryArea.setWrapStyleWord(true);
    clearButton.setPreferredSize(new Dimension(125, 25));
    clearButton.setText("Clear Journal Entry");
    clearButton.addActionListener(new JournalFrame_clearButton_actionAdapter(this));
    saveButton.setText("Save Journal Entry");
    saveButton.addActionListener(new JournalFrame_saveButton_actionAdapter(this));
    this.setTitle("Journal");
    gridLayout3.setColumns(1);
    gridLayout3.setRows(0);
    this.getContentPane().add(datePanel, BorderLayout.NORTH);
    this.getContentPane().add(radioPanel, BorderLayout.WEST);
    this.getContentPane().add(textAreaPanel, BorderLayout.CENTER);
    this.getContentPane().add(buttonPanel, BorderLayout.EAST);
    entryType.add(personalButton);
    entryType.add(businessButton);
    datePanel.add(dateLabel);
    datePanel.add(dateField);
    radioPanel.add(personalButton, null);
    radioPanel.add(businessButton, null);
    textAreaPanel.add(entryArea, null);
    buttonPanel.add(clearButton, null);
    buttonPanel.add(saveButton, null);
    this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
    statusPanel.add(status, null);
    this.pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    private void saveEntry() throws IOException{
    if( personalButton.isSelected())
    String file = "Personal.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    entryArea.getText();
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    else if (businessButton.isSelected())
    String file = "Business.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    void clearButton_actionPerformed(ActionEvent e) {
    dateField.setText("");
    entryArea.setText("");
    status.setText("");
    void saveButton_actionPerformed(ActionEvent e){
    try{
    saveEntry();
    }catch(IOException error){
    status.setText("Error: Could not save journal entry");
    void personalButton_actionPerformed(ActionEvent e) {
    class JournalFrame_clearButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_clearButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.clearButton_actionPerformed(e);
    class JournalFrame_saveButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_saveButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.saveButton_actionPerformed(e);
    class JournalFrame_personalButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_personalButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.personalButton_actionPerformed(e);
    public class JournalApp {
    public static void main(String args[])
    JournalFrame journal = new JournalFrame();
    journal.setVisible(true);
    }

    Bet you're trying "java JournalFrame" when you need to "java JournalApp".
    Couple pointers toward good code.
    1) Use white space (extra returns) to separate your code into logical "paragraphs" of thought.
    2) Add comments. At a minimum a comment at the beginning should name the file, state its purpose, identify the programmer and date written. A comment at the end should state that you've reached the end. In the middle, any non-obvious code should be commented and closing braces or parens should have a comment stating what they close (if there is non-trivial separation from where they open).
    Here's a sample:
    // JournalFrame.java - this does ???
    // saisoft, 4/18/03
    // constructor
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(borderLayout1);
        radioPanel.setLayout(gridLayout1);
        statusPanel.setLayout(flowLayout1);
        textAreaPanel.setLayout(gridLayout2);
        buttonPanel.setLayout(gridLayout3);
        personalButton.setSelected(true);
        personalButton.setText("Personal");
        personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
        businessButton.setText("Business");
        status.setText("");
        entryArea.setText("");
        entryArea.setColumns(10);
        entryArea.setLineWrap(true);
        entryArea.setRows(30);
        entryArea.setWrapStyleWord(true);
    } // end constructor
    // end JournalFrame.java3) What would you expect to gain from that inner class? It might be more cool, but would it be more clear? I give the latter (clarity) a lot of importance.

  • Main method not found and how to implement events in an inner class

    How would I put all the event handling methods in an inner class and I have another class that just that is just a main function, but when i try to run the project, it says main is not found. Here are the two classes, first one sets up everything and the second one is just main.
    mport java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class JournalFrame extends JFrame {
    private JLabel dateLabel = new JLabel("Date: ");
    private JTextField dateField = new JTextField(20);
    private JPanel datePanel = new JPanel(new FlowLayout());
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel radioPanel = new JPanel();
    JPanel statusPanel = new JPanel();
    JPanel textAreaPanel = new JPanel();
    JPanel buttonPanel = new JPanel();
    GridLayout gridLayout1 = new GridLayout();
    FlowLayout flowLayout1 = new FlowLayout();
    GridLayout gridLayout2 = new GridLayout();
    GridLayout gridLayout3 = new GridLayout();
    JRadioButton personalButton = new JRadioButton();
    JRadioButton businessButton = new JRadioButton();
    JLabel status = new JLabel();
    JTextArea entryArea = new JTextArea();
    JButton clearButton = new JButton();
    JButton saveButton = new JButton();
    ButtonGroup entryType = new ButtonGroup();
    public JournalFrame(){
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void initWidgets(){
    private void jbInit() throws Exception {
    this.getContentPane().setLayout(borderLayout1);
    radioPanel.setLayout(gridLayout1);
    statusPanel.setLayout(flowLayout1);
    textAreaPanel.setLayout(gridLayout2);
    buttonPanel.setLayout(gridLayout3);
    personalButton.setSelected(true);
    personalButton.setText("Personal");
    personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
    businessButton.setText("Business");
    status.setText("");
    entryArea.setText("");
    entryArea.setColumns(10);
    entryArea.setLineWrap(true);
    entryArea.setRows(30);
    entryArea.setWrapStyleWord(true);
    clearButton.setPreferredSize(new Dimension(125, 25));
    clearButton.setText("Clear Journal Entry");
    clearButton.addActionListener(new JournalFrame_clearButton_actionAdapter(this));
    saveButton.setText("Save Journal Entry");
    saveButton.addActionListener(new JournalFrame_saveButton_actionAdapter(this));
    this.setTitle("Journal");
    gridLayout3.setColumns(1);
    gridLayout3.setRows(0);
    this.getContentPane().add(datePanel, BorderLayout.NORTH);
    this.getContentPane().add(radioPanel, BorderLayout.WEST);
    this.getContentPane().add(textAreaPanel, BorderLayout.CENTER);
    this.getContentPane().add(buttonPanel, BorderLayout.EAST);
    entryType.add(personalButton);
    entryType.add(businessButton);
    datePanel.add(dateLabel);
    datePanel.add(dateField);
    radioPanel.add(personalButton, null);
    radioPanel.add(businessButton, null);
    textAreaPanel.add(entryArea, null);
    buttonPanel.add(clearButton, null);
    buttonPanel.add(saveButton, null);
    this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
    statusPanel.add(status, null);
    this.pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    private void saveEntry() throws IOException{
    if( personalButton.isSelected())
    String file = "Personal.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    entryArea.getText();
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    else if (businessButton.isSelected())
    String file = "Business.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
    bw.write("Date: " + dateField.getText());
    bw.newLine();
    bw.write(entryArea.getText());
    bw.newLine();
    bw.flush();
    bw.close();
    status.setText("Journal Entry Saved");
    void clearButton_actionPerformed(ActionEvent e) {
    dateField.setText("");
    entryArea.setText("");
    status.setText("");
    void saveButton_actionPerformed(ActionEvent e){
    try{
    saveEntry();
    }catch(IOException error){
    status.setText("Error: Could not save journal entry");
    void personalButton_actionPerformed(ActionEvent e) {
    class JournalFrame_clearButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_clearButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.clearButton_actionPerformed(e);
    class JournalFrame_saveButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_saveButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.saveButton_actionPerformed(e);
    class JournalFrame_personalButton_actionAdapter implements java.awt.event.ActionListener {
    JournalFrame adaptee;
    JournalFrame_personalButton_actionAdapter(JournalFrame adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.personalButton_actionPerformed(e);
    public class JournalApp {
    public static void main(String args[])
    JournalFrame journal = new JournalFrame();
    journal.setVisible(true);
    }

    Here is the complete code (with crappy indentation) :
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class JournalFrame extends JFrame {
        private JLabel dateLabel = new JLabel("Date: ");
        private JTextField dateField = new JTextField(20);
        private JPanel datePanel = new JPanel(new FlowLayout());
        BorderLayout borderLayout1 = new BorderLayout();
        JPanel radioPanel = new JPanel();
        JPanel statusPanel = new JPanel();
        JPanel textAreaPanel = new JPanel();
        JPanel buttonPanel = new JPanel();
        GridLayout gridLayout1 = new GridLayout();
        FlowLayout flowLayout1 = new FlowLayout();
        GridLayout gridLayout2 = new GridLayout();
        GridLayout gridLayout3 = new GridLayout();
        JRadioButton personalButton = new JRadioButton();
        JRadioButton businessButton = new JRadioButton();
        JLabel status = new JLabel();
        JTextArea entryArea = new JTextArea();
        JButton clearButton = new JButton();
        JButton saveButton = new JButton();
        ButtonGroup entryType = new ButtonGroup();
        public JournalFrame(){
            try {
                jbInit();
            catch(Exception e){
                e.printStackTrace();
        private void initWidgets(){
        private void jbInit() throws Exception {
            this.getContentPane().setLayout(borderLayout1);
            radioPanel.setLayout(gridLayout1);
            statusPanel.setLayout(flowLayout1);
            textAreaPanel.setLayout(gridLayout2);
            buttonPanel.setLayout(gridLayout3);
            personalButton.setSelected(true);
            personalButton.setText("Personal");
            personalButton.addActionListener(new JournalFrame_personalButton_actionAdapter(this));
            businessButton.setText("Business");
            status.setText("");
            entryArea.setText("");
            entryArea.setColumns(10);
            entryArea.setLineWrap(true);
            entryArea.setRows(30);
            entryArea.setWrapStyleWord(true);
            clearButton.setPreferredSize(new Dimension(125, 25));
            clearButton.setText("Clear Journal Entry");
            clearButton.addActionListener(new JournalFrame_clearButton_actionAdapter(this));
            saveButton.setText("Save Journal Entry");
            saveButton.addActionListener(new JournalFrame_saveButton_actionAdapter(this));
            this.setTitle("Journal");
            gridLayout3.setColumns(1);
            gridLayout3.setRows(0);
            this.getContentPane().add(datePanel, BorderLayout.NORTH);
            this.getContentPane().add(radioPanel, BorderLayout.WEST);
            this.getContentPane().add(textAreaPanel, BorderLayout.CENTER);
            this.getContentPane().add(buttonPanel, BorderLayout.EAST);
            entryType.add(personalButton);
            entryType.add(businessButton);
            datePanel.add(dateLabel);
            datePanel.add(dateField);
            radioPanel.add(personalButton, null);
            radioPanel.add(businessButton, null);
            textAreaPanel.add(entryArea, null);
            buttonPanel.add(clearButton, null);
            buttonPanel.add(saveButton, null);
            this.getContentPane().add(statusPanel, BorderLayout.SOUTH);
            statusPanel.add(status, null);
            this.pack();
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        private void saveEntry() throws IOException{
            if( personalButton.isSelected()){
                String file = "Personal.txt";
                BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
                entryArea.getText();
                bw.write("Date: " + dateField.getText());
                bw.newLine();
                bw.write(entryArea.getText());
                bw.newLine();
                bw.flush();
                bw.close();
                status.setText("Journal Entry Saved");
            else if (businessButton.isSelected()){
                String file = "Business.txt";
                BufferedWriter bw = new BufferedWriter(new FileWriter(file,true));
                bw.write("Date: " + dateField.getText());
                bw.newLine();
                bw.write(entryArea.getText());
                bw.newLine();
                bw.flush();
                bw.close();
                status.setText("Journal Entry Saved");
        void clearButton_actionPerformed(ActionEvent e) {
            dateField.setText("");
            entryArea.setText("");
            status.setText("");
        void saveButton_actionPerformed(ActionEvent e){
            try{saveEntry();}catch(IOException error){
                status.setText("Error: Could not save journal entry");
        void personalButton_actionPerformed(ActionEvent e) {
        class JournalFrame_clearButton_actionAdapter implements java.awt.event.ActionListener {
        JournalFrame adaptee;
        JournalFrame_clearButton_actionAdapter(JournalFrame adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.clearButton_actionPerformed(e);
    class JournalFrame_saveButton_actionAdapter implements java.awt.event.ActionListener {
        JournalFrame adaptee;
        JournalFrame_saveButton_actionAdapter(JournalFrame adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.saveButton_actionPerformed(e);
    class JournalFrame_personalButton_actionAdapter implements java.awt.event.ActionListener {
        JournalFrame adaptee;
        JournalFrame_personalButton_actionAdapter(JournalFrame adaptee) {
            this.adaptee = adaptee;
        public void actionPerformed(ActionEvent e) {
            adaptee.personalButton_actionPerformed(e);
    }BadLands

  • Why can't inner classes have static methods?

    I just tried to add a static method to an inner class, which would have been useful for extracting constants about said inner class, and it turns out that is not allowed.
    Of course I have other ways to code what I wanted, but I'm curious as to why this restriction was set in place. Anybody know?

    Probably because an inner class is tied to an instance of the enclosing class. I think that, conceptually at least, the inner class' definition itself only exists in the context of an instance of the enclosing class. While I'm sure it would have been technically possible to allow it, it would be confusing and not make a whole lot of sense--what is the static context for the inner class, since the class only exists in a non-static context?

  • Inner class access to its creator

    Hi there,
    From a subclass of Action I have created as a (non-static) inner class of a JFrame, I wish to reference the parent JFrame in a JFileChooser invocation, so something like:JFileChooser.showSaveDialog(**this**);with **this** being the parent JFrame.
    One option I can think of is to pass through "this" when I instantiate the action, but I wondered if there was a language construction that provided this information directly.
    I tried a search through the forums using "parent of an inner class" but found nothing useful. Is there a mechanism to provide this, or is passing "this" through to the inner class the only option?
    Thanks for any help you can provide.
    Tim

    To access wrapper instance of inner class, you can use WRAPPER_INSTANCE_CLASS.this keyword.
    For example:
    public class a {
       int value = 0;
       public void doSomething() {
          Object dummy = new Object() {
              public String toString() {
                  a.this.setSomething(10);
                  return a.this.toString();
          System.out.println(dummy);
       public void setSomething(int x) {
          value = x;
       public String toString() {
          return "class a, the value now is " + value;
       public static void main (String s[]) {
           new a().doSomething();
    }note that I use a.this.setSomething(10);
    a is the wrapper class, so a.this refers to the wrapper instance, not current instance.
    rgds,
    Alex

  • Methods or inner classes?

    Is there much difference, performance wise between a class method and an inner class? I am writing a 3d application where performance is of the essence, I can either put my code in seperate moethds or inner classes. The code is more managable when I use inner classes but I was wondering whether this was slower.
    Thanks.

    blink I presume your inner classes would have methods, right? Anyway,
    1. Don't prematurely optimise.
    2. Don't prematurely optimise.
    3. Object creation is the only thing which would cause any extra cost. But it's extremely unlikely to be a bottleneck.

  • Don't understand Inner Classes and how to use it

    Hi
    As you guess i 'am a newbie!
    I don't understand Inner Classes, particulary members(methods & fields) that an Inner method is able to manipulate.
    So I know that the methods of an Inner class (respectively Outer Class) instance can access members (private or public) of an instance of the Outer Class (respectively Inner Class).
    I tried to answer to a quizz : http://java.sun.com/developer/onlineTraining/new2java/supplements/quizzes/January03.html
    In the following class definition, which variables are inaccessible within the method of the inner class?
    class Test1 {
       public static int a = 1;
       private static int b = 2;
       public int c = 3;
       private int d = 4;
       public static class Inner {
         int e = 5;
         public void aMethod(int f) {
           int g = 6;
           // What can't be accessed here?
    }A.      b, c, d
    B.      c, d
    C.      b, c, d, f
    D.      None of them
    In my opinion members (public or private) of the Outer Class can be accessed by methods of the Inner Class; e.g: a, b, c,d thus for me the answer is D.
    Obviously i'm wrong, but why?

    Hi
    As you guess i 'am a newbie!
    I don't understand Inner Classes, particulary
    members(methods & fields) that an Inner method is
    able to manipulate.
    So I know that the methods of an Inner class
    (respectively Outer Class) instance can access
    members (private or public) of an instance of the
    Outer Class (respectively Inner Class).
    I tried to answer to a quizz :
    http://java.sun.com/developer/onlineTraining/new2java/
    supplements/quizzes/January03.html
    In the following class definition, which variables
    are inaccessible within the method of the inner
    class?
    class Test1 {
    public static int a = 1;
    private static int b = 2;
    public int c = 3;
    private int d = 4;
    public static class Inner {
    int e = 5;
    public void aMethod(int f) {
    int g = 6;
    // What can't be accessed here?
    }A.      b, c, d
    B.      c, d
    C.      b, c, d, f
    D.      None of them
    In my opinion members (public or private) of the
    Outer Class can be accessed by methods of the Inner
    Class; e.g: a, b, c,d thus for me the answer is
    D.
    Obviously i'm wrong, but why?Inner class method can access all the private members of the class. But the inner class is static. So the non-static members cannot be accessed directly (i.e. c and d).
    ***Annie***

  • Inner class jstl

    hello all...
    I have a class for my transfer object and have an inner calss in it ...can anyone help me in accessing the getter setter methods in my inner class in my jsp page...
    help is greatly appreciated...
    Thanks

    Add a getter/setter for that inner class in the parent class.

Maybe you are looking for