我想知道当变量的值依赖于动作侦听器时如何使变量成为全局变量。为了回应评论,我需要能够在我的代码中的任何地方使用变量及其值。
import javax.swing.*;
import java.awt.*;
public class example {
public static String a;
public static void main(String[] args) {
final JFrame f = new JFrame();
f.setSize(200, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
JPanel p = new JPanel();
f.add(p);
final JTextField tf = new JTextField("write stuff");
p.add(tf);
tf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
a = tf.getText();
//How would I make this global?
}
});
//and I would use it in this JLabel
JLable l = new JLabel(a);
p.add(a);
}
}