• Announcements

Archived

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

Swing exam Q- whats wrong with code fragment

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");

public void actionPerformed(ActionEvent ev) {

label.setText("Goodbye");

}

});

}

}


Share on other sites
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 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

• Forum Statistics

• Total Topics
627697
• Total Posts
2978680

• 20
• 14
• 12
• 10
• 12