Archived

This topic is now archived and is closed to further replies.

Swing exam Q- whats wrong with code fragment

This topic is 5597 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Im having trouble with the following question ---------------------------------- The following Java code is meaningless and will fail to compile. Explain why it’s meaningless in terms of what the programmer presumably expected to happen at runtime, and propose the simplest way to fix it. (Assume that all necessary types have been imported correctly.) ---------------------------- The only problem I can think of is JLabel should be declared final, thats why it wont compile but why would it be meaningless. Any suggestions?
  
public class Question {

   public void installComponents(Container pane) {

      JLabel label = new JLabel("Hello");

      JButton button = new JButton("Go away");

      button.addActionListener(new ActionListener() {

         public void actionPerformed(ActionEvent ev) {

            label.setText("Goodbye");

         }

      });

      pane.add(label);

      pane.add(button);

   }

}
  

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
I would think that you would need to make label a member variable, instead of a method variable.

In the listener you are manipulating it, even though it _should_ (AFAIK) be out of scope.

I would think anyway.

Share this post


Link to post
Share on other sites
After a cursory glance, I would say the problem is the local variable "label", although it is known in the installComponents method, the actionPerformed method knows diddly-aquat (nothing) about it. Why? Well because "label" is in the local scope of installComponents, and has gone out of scope by the time you get to actionPerformed

NightWraith

Share this post


Link to post
Share on other sites