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);
}
}
Swing exam Q- whats wrong with code fragment
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?
August 15, 2002 11:15 PM
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.
In the listener you are manipulating it, even though it _should_ (AFAIK) be out of scope.
I would think anyway.
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
NightWraith
NightWraith
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement