Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 27

Thread: Object-oriented applet

  1. #1
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Object-oriented applet

    I'm trying to get these two classes to work together:

    import java.applet.*;
    import java.awt.*;
     
    /*
    <applet code = Buttons.java width = 100 height = 100> </applet>
    */
     
    public class Buttons extends Applet
    {
        Label label = new Label("Push the button!");
        Button button = new Button("Push me!");
        Pushed pushed = new Pushed();
     
        public void init ()
        {
             this.add(button);
             this.add(label);
        }
    }

    import java.awt.event.*;
     
    public class Pushed implements ActionListener
    {
         Buttons buttons = new Buttons();
     
         buttons.addActionListener(buttons.button);
     
         public void actionPerformed(ActionEvent ae)
         {
              String actionStr = ae.getActionCommand();
     
              if (actionStr.equals("Push Me!"))
              {
                   System.out.println("Stop pushing my buttons!");
              }
         }  
    }

    Right now, Buttons compiles only when the the Pushed object is commented out and tells me that that it expects identifiers in front of the occurrences of "buttons.button" and that the package "buttons" cannot be found when the Pushed object is included in the code. The compiler also says that it expects identifiers in front of the occurrences of "buttons.button" when it tries to compile Pushed.

    Can I have a "static" GUI class that simply extends the Applet class and a "dynamic" engine class that only implements the ActionListener interface?

    Or do I have to have both classes implement ActionListener so that I can have the calls to *.assActionListener in side an initialization block and can pass an ActionEvent to Pushed?


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Object-oriented applet

    Please copy the full text of the error messages and paste them here. Don't edit them.

    Where do you add an actionListener to the Button object?

  3. #3
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Object-oriented applet

    Quote Originally Posted by Norm View Post
    Please copy the full text of the error messages and paste them here. Don't edit them.
    Here are the compiler error I get when I try to compile:

    1. Buttons.java with the Pushed object in line 12 of Buttons.java not commented out
      .\Pushed.java:7: <identifier> expected
           buttons.addActionListener(buttons.button);
                                                ^
      .\Pushed.java:7: <identifier> expected
           buttons.addActionListener(buttons.button);
                                                                    ^
      .\Pushed.java:7: package buttons does not exist
           buttons.addActionListener(buttons.button);
                                                ^
      .\Pushed.java:7: package buttons does not exist
           buttons.addActionListener(buttons.button);
                                                                    ^
      4 errors
    2. Pushed.java with the Pushed object in line 12 of Buttons.java commented out
      Pushed.java:7: <identifier> expected
           buttons.addActionListener(buttons.button);
                                               ^
      Pushed.java:7: <identifier> expected
           buttons.addActionListener(buttons.button);
                                                                    ^
      2 errors
    3. Pushed.java with the Pushed object in line 12 of Buttons.java not commented out
      Pushed.java:7: <identifier> expected
           buttons.addActionListener(buttons.button);
                                               ^
      Pushed.java:7: <identifier> expected
           buttons.addActionListener(buttons.button);
                                                                    ^
      2 errors


    As I mentioned in my OP, the Buttons.java compiles without error when the Pushed object in line 12 of Buttons.java is commented out. In fact, the GUI elements load in the appletviewer , but no action is performed when the button is pressed.

    Quote Originally Posted by Norm View Post
    Where do you add an actionListener to the Button object?
    I tried to add the ActionListener to the Button object by adding it to the Button instance in the Buttons object I created in line 7 of Pushed.java:

    buttons.addActionListener(buttons.button);

    This is the line that return all the compiler warnings, so I'm not sure if my syntax is correct or if what I am trying to do is possible in the way that I am trying to do it.
    Last edited by mjpam; September 14th, 2010 at 01:15 PM.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Object-oriented applet

    Does the Buttons class have a method: addActionListener()?

    What method contains the line with the errors?
    Last edited by Norm; September 14th, 2010 at 01:20 PM.

  5. #5
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Object-oriented applet

    Executable code has to be inside of a method or constructor (or static/instance initializer). In the body f the class, outside of any method / constructor / initializer you can have only member declarations.

    Put that line buttons.addActionListener(buttons.button); inside a method or constructor.

    db
    Last edited by Darryl.Burke; September 14th, 2010 at 01:18 PM. Reason: Plus what Norm said

  6. #6
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Object-oriented applet

    Quote Originally Posted by Norm View Post
    The button member of the Buttons class is not an ActionListener. The Pushed class is an ActionListener. To get a reference to a Pushed object in the Pushed class, use the this reference.
    A reference to a Pushed object?

    How do I add an ActionListener to the Button object in the GUI if the Pushed object contains no Button objects?

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Object-oriented applet

    Does the Buttons class have a method: addActionListener()?

  8. #8
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Object-oriented applet

    Quote Originally Posted by Norm View Post
    Does the Buttons class have a method: addActionListener()?
    Not unless I implement the ActionListener interface on it.

    When I implement ActionListener on Buttons and put buttons.addActionListener(buttons.button) in side the constructor in the Pushed class, the code looks like this:

    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
     
    /*
    <applet code = Buttons.java width = 100 height = 100> </applet>
    */
     
    public class Buttons extends Applet implements ActionListener
    {
        Label label = new Label("Push the button!");
        Button button = new Button("Push me!");
        Pushed pushed = new Pushed();
     
        public void init ()
        {
             this.add(button);
             this.add(label);
        }
     
        public void actionPerformed(ActionEvent ae)
        {
     
        }
    }

    import java.awt.event.*;
     
    public class Pushed implements ActionListener
    {
         Buttons buttons = new Buttons();
     
         Pushed()
         {
             buttons.addActionListener(buttons.button);
         }
     
         public void actionPerformed(ActionEvent ae)
         {
              String actionStr = ae.getActionCommand();
     
              if (actionStr.equals("Push Me!"))
              {
                   System.out.println("Stop pushing my buttons!");
              }
         }  
    }

    The compiler returns another error:

    Pushed.java:9: cannot find symbol
    symbol  : method addActionListener(java.awt.Button)
    location: class Pushed
             this.addActionListener(buttons.button);
                 ^
    1 error

    I thought that I could access the addActionListener method from an instance of the Buttons class if I implemented the ActionListener interface on the Buttons object.

    That said, I understand how to make the applet work if I wrote it all in one class, but nowI would like to understand how to get two class to create one applet.

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Object-oriented applet

    Does the Buttons class have a method: addActionListener()?

    Not unless I implement the ActionListener interface on it.
    You're missing my point. The Buttons class extends Applet. Neither of those two classes has a method: addActionListener

    cannot find symbol
    symbol : method addActionListener(java.awt.Button)
    This last error message you posted shows another class that does NOT have the method: addActionListener

    You need to read the API doc for the classes you are using to see if they have a method you are trying to use. Some do, many don't.

  10. #10
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Object-oriented applet

    I'm confused because, in the past, I have been able to add ActionListeners to Button objects in Applet classes.

    For instance the following code compiles and runs as desired:

    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
     
    /*
    <applet code = "CalculatorApplet2" width = 225 height = 300>
    </applet>
    */
     
    public class CalculatorApplet2 extends Applet implements ActionListener
    {
         private TextField fArgTxt;
         private TextField sArgTxt;
         private TextField ansTxt;
     
         public void init ()
         {
              // Construct the TextFields
     
              this.fArgTxt = new TextField(25);
              this.sArgTxt = new TextField(25);
              this.ansTxt = new TextField(25);
              Button adds = new Button("+");
              Button subs = new Button("-");
              Button mults = new Button("*");
              Button divs = new Button("/");
     
              // add the button to the layout
              this.add(fArgTxt);
              this.add(sArgTxt);
              this.add(ansTxt);
              this.add(adds);
              this.add(subs);
              this.add(mults);
              this.add(divs);
     
              fArgTxt.addActionListener(this);
              sArgTxt.addActionListener(this);
              adds.addActionListener(this);
              subs.addActionListener(this);
              mults.addActionListener(this);
              divs.addActionListener(this);
     
     
         }
     
         public void actionPerformed(ActionEvent ae)
         {
              double fArgVal = Double.parseDouble(fArgTxt.getText());
              double sArgVal = Double.parseDouble(sArgTxt.getText());
              String actionStr = ae.getActionCommand();
     
              if (actionStr.equals("+"))
              {
                   double sumVal = fArgVal + sArgVal;
                   ansTxt.setText("" + sumVal);
              }
              if (actionStr.equals("-"))
              {
                   double difVal = fArgVal - sArgVal;
                   ansTxt.setText("" + difVal);
              }
              if (actionStr.equals("*"))
              {
                   double prodVal = fArgVal * sArgVal;
                   ansTxt.setText("" + prodVal);
              }
              if (actionStr.equals("/"))
              {
                   double quotVal = fArgVal / sArgVal;
     
                   if (Double.isInfinite(quotVal))
                   {
                        ansTxt.setText("Error: Division by zero");
                   }
                   else
                   {
                        ansTxt.setText("" + quotVal);
                   }
              }
         }
    }

    I understand everything is done all in one class here but adding the ActionListeners does not cause the compiler errors that the compiling the code in the OP or the following code does:

    import java.applet.*;
    import java.awt.*;
     
    /*
    <applet code = ButtonPushed.java width = 100 height = 100>
    </applet>
    */
     
    public class ButtonPushed extends Applet implements ActionListener
    {
         Button button = new Button("Push me!");
         Label label = new Label("Push the button");
     
         public void init()
         {
              this.add(button);
              this.add(label);
     
              button.addActionListener(this);
              label.addActionListener(this);
         }
     
         public void actionPerformed(ActionEvent ae)
         {
              String actionStr = ae.getActionCommand();
     
              if (ae.equals("Push Me!"))
              {
                  label.setText("Don't push my buttons!");
              }
         }
    }

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Object-oriented applet

    I have been able to add ActionListeners to Button
    Yes, the Button class has an addActionListener method

  12. #12
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Object-oriented applet

    Quote Originally Posted by Norm View Post
    Yes, the Button class has an addActionListener method
    So why can't I add an ActionListener to a Button object inside the Buttons object?

    I understand that I can't add the ActionListener to the Buttons buttons object because the class of which it is an instance does not have the addActionListener() method, but the class of which buttons.button is an instance (i.e., the Button class) does have an addActionListener() method.

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Object-oriented applet

    add an ActionListener to a Button object inside the Buttons object
    You can do that.
    add the ActionListener to the Buttons buttons object because the class of which it is an instance does not have the addActionListener() method, but the class of which buttons.button is an instance (i.e., the Button class) does have an addActionListener() method.
    Look at how you are calling the addActionListener method. What type is the argument passed in the method call?

  14. #14
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Object-oriented applet

    Quote Originally Posted by Norm View Post
    Look at how you are calling the addActionListener method. What type is the argument passed in the method call?
    I see it now: the documentation say the addActionListener() method must take an ActionListener argument.

    I'm sorry that my understanding is torturously slow in coming. I think that part of my problem was that I was interpreting the this in button.addActionListener(this) to being saying "add an ActionListener to this button" and not "add this ActionListner to button". I also seem to have missed the fact that addActionListener() took an ActionListener type argument, despite having read through the documentation several times.

    That said, the applet seems to be throwing some sort of run-time exception because it prints the following text repeatedly:

            at Buttons.<init>(Buttons.java:13)
            at Pushed.<init>(Pushed.java:5)

    I don't know what is happening at those lines, because the message is run off the accessible window before I can read it.

  15. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Object-oriented applet

    Your code is recursively calling itself. Add print outs to both of the constructors to see what I mean.


    The following doesn't work because the problem is outside of the constructors.


    To see where each constructor is called from add this statement to both constructors:
    try{throw new Exception("who called?");}catch(Exception x){x.printStackTrace();}

    It will print a stack trace showing who called
    Last edited by Norm; September 14th, 2010 at 05:33 PM.

  16. #16
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Object-oriented applet

    Quote Originally Posted by Norm View Post
    Your code is recursively calling itself. Add print outs to both of the constructors to see what I mean.


    The following doesn't work because the problem is outside of the constructors.


    To see where each constructor is called from add this statement to both constructors:
    try{throw new Exception("who called?");}catch(Exception x){x.printStackTrace();}

    It will print a stack trace showing who called
    Can you show where to add the try/throw/catch blocks to get the stack trace to print?

    I have modified my code like this:

    import java.applet.*;
    import java.awt.*;
     
    /*
    <applet code = Buttons.java width = 100 height = 100> </applet>
    */
     
    public class Buttons extends Applet
    {
        Label label = new Label("Push the button!");
        Button button = new Button("Push me!");
        Pushed pushed = new Pushed();
     
     
        public Buttons()
        {
            try
            {
                throw new Exception("who called?");
             }
             catch(Exception x)
             {
                  x.printStackTrace()
             }
         }
     
        public void init ()
        {
             this.add(button);
             this.add(label);
        }
    }
    import java.awt.event.*;
     
    public class Pushed implements ActionListener
    {
         public Pushed ()
         {
              Buttons buttons = new Buttons();
              (buttons.button).addActionListener(this);
              try
              {
                   throw new Exception("who called?");
              }
              catch(Exception x)
              {
                   x.printStackTrace();
              }
         }
     
         public void actionPerformed(ActionEvent ae)
         {
              String actionStr = ae.getActionCommand();
     
              if (actionStr.equals("Push Me!"))
              {
                   System.out.println("Stop pushing my buttons!");
              }
         }  
    }

    It still only prints what I noted above.
    Last edited by mjpam; September 14th, 2010 at 06:36 PM.

  17. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Object-oriented applet

    Do you see the recursion?

    The Buttons class creates a Pushed object:
    Pushed pushed = new Pushed();

    The Pushed class creates a Buttons object:
    Buttons buttons = new Buttons();

    The Buttons class creates a Pushed object:
    Pushed pushed = new Pushed();

    The Pushed class creates a Buttons object:
    Buttons buttons = new Buttons();

    The Buttons class creates a Pushed object:
    Pushed pushed = new Pushed();

    The Pushed class creates a Buttons object:
    Buttons buttons = new Buttons();

    The Buttons class creates a Pushed object:
    Pushed pushed = new Pushed();

    The Pushed class creates a Buttons object:
    Buttons buttons = new Buttons();

    The Buttons class creates a Pushed object:
    Pushed pushed = new Pushed();

    The Pushed class creates a Buttons object:
    Buttons buttons = new Buttons();
    ....
    until the system runs out of memory.

    You need to think through when to create what objects in what order.

  18. #18
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Object-oriented applet

    Quote Originally Posted by Norm View Post
    Do you see the recursion?
    until the system runs out of memory.

    You need to think through when to create what objects in what order.
    I should have been more clear. I did see the recursion, but I was asking about why it was throwing exceptions and how I could get it to print the exceptions and their causes.

  19. #19
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Object-oriented applet

    why it was throwing exceptions and how I could get it to print the exceptions and their causes.
    What exceptions is it throwing? Please copy and paste the error message here.

  20. #20
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Object-oriented applet

    Quote Originally Posted by Norm View Post
    What exceptions is it throwing? Please copy and paste the error message here.
    I don't know and I can't copy and paste them here because they have been run off the window before I can stop the applet.

    All I get is:

            at Pushed.<init>(Pushed.java:7)
            at Buttons.<init>(Buttons.java:12)

    I'm sorry that I am not more specific, but the applet runs too fast for me to capture what ever "at Pushed.<init>(Pushed.java:7)" and "at Buttons.<init>(Buttons.java:12) " refers to.

  21. #21
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Object-oriented applet

    What you've posted is the call stack which is verrrrrrrrrrrrrrrry long because of the recursion.

    Now look at your code and play computer with it. Where does the cross calls to the creation of the other class occur?
    Break that and the recursion will stop.

  22. #22
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Object-oriented applet

    Here are the exceptions that the applet throws:

    java.lang.Exception: who called?
            at Buttons.<init>(Buttons.java:20)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
     
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
            at java.lang.Class.newInstance0(Class.java:355)
            at java.lang.Class.newInstance(Class.java:308)
            at sun.applet.AppletPanel.createApplet(AppletPanel.java:785)
            at sun.applet.AppletPanel.runLoader(AppletPanel.java:714)
            at sun.applet.AppletPanel.run(AppletPanel.java:368)
            at java.lang.Thread.run(Thread.java:619)

  23. #23
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Object-oriented applet

    java.lang.Exception: who called?
    That's the code I had you put in for debugging. You can comment it out now. Its for the case where you want to see the call stack to show who called a method.

  24. #24
    Member
    Join Date
    Jun 2010
    Posts
    75
    Thanks
    7
    Thanked 1 Time in 1 Post

    Default Re: Object-oriented applet

    Quote Originally Posted by Norm View Post
    That's the code I had you put in for debugging. You can comment it out now. Its for the case where you want to see the call stack to show who called a method.
    So is the applet actually throwing an exception when the code is commented out?

    The problem that I am having is that, with the call to the Pushed constructor in the Buttons class commented out, there is no Pushed object that handles the ActionEvent created when I push the "Push Me!" button. Or so I think, because the action in the actionPerformed() method in the Pushed object is not performed (i.e., "Stop pushing my buttons!" is not printed to the console.

    How do I get the objects to communicate without creating an infinite loop?

  25. #25
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,166
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: Object-oriented applet

    You need to pass a reference to one class to the other. For example in Buttons pass a reference to itself (this) in the constructor of the Pushed class.
    Pushed pushed = new Pushed(this);
    and in the Pushed class, receive the reference in a constructor:
    Pushed(Buttons b) {

Page 1 of 2 12 LastLast

Similar Threads

  1. 2D Object makes my object smaller, Why?
    By MassiveResponse in forum What's Wrong With My Code?
    Replies: 2
    Last Post: May 15th, 2010, 02:33 PM
  2. TCP Client Server: Object Oriented
    By nffc luke in forum Object Oriented Programming
    Replies: 2
    Last Post: April 28th, 2010, 06:39 PM
  3. applet img
    By wolfgar in forum Java Theory & Questions
    Replies: 5
    Last Post: April 7th, 2010, 09:14 PM
  4. Object Oriented Programming request please helpp...
    By dini-x in forum Object Oriented Programming
    Replies: 3
    Last Post: April 1st, 2010, 12:57 AM
  5. Object Oriented program, no output
    By boardbreaker in forum What's Wrong With My Code?
    Replies: 2
    Last Post: November 17th, 2009, 11:11 PM