J
jim
I was told that the variable accessed inside a anonymous inner class
needs to be static.
However the followign code from Thinking in java 3 works fine.
Why?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import com.bruceeckel.swing.*;
public class Button2b extends JApplet {
private JButton
b1 = new JButton("Button 1"),
b2 = new JButton("Button 2");
private JTextField txt = new JTextField(10);
private ActionListener bl = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = ((JButton)e.getSource()).getText();
txt.setText(name); ------question? the txt is not final
but no complain from compiler
}
};
public void init() {
b1.addActionListener(bl);
b2.addActionListener(bl);
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(b1);
cp.add(b2);
cp.add(txt);
}
public static void main(String[] args) {
Console.run(new Button2b(), 200, 75);
}
} ///:~
needs to be static.
However the followign code from Thinking in java 3 works fine.
Why?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import com.bruceeckel.swing.*;
public class Button2b extends JApplet {
private JButton
b1 = new JButton("Button 1"),
b2 = new JButton("Button 2");
private JTextField txt = new JTextField(10);
private ActionListener bl = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = ((JButton)e.getSource()).getText();
txt.setText(name); ------question? the txt is not final
but no complain from compiler
}
};
public void init() {
b1.addActionListener(bl);
b2.addActionListener(bl);
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(b1);
cp.add(b2);
cp.add(txt);
}
public static void main(String[] args) {
Console.run(new Button2b(), 200, 75);
}
} ///:~