import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyTest_12{
public static void main(String []args){
JTextField txtA=new JTextField("请单击确定按钮");
JButton btOk=new JButton("确定");
ActionListener myal=new myActionListener();
btOk.addActionListener(myal);
JPanel p=new JPanel();
p.add(txtA);
p.add(btOk);
JFrame f=new JFrame();
f.setSize(200,300);
Container contentPane=f.getContentPane();
contentPane.add(p);
f.show();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class myActionListener implements ActionListener{
public myActionListener(){
}
public void actionPerformed(ActionEvent e){
JButton b=(JButton)e.getSource();
b.setText("OK");
}
}
------解决方案--------------------
public class MyTest_12{
//使用静态全局变量
static JTextField txtA=new JTextField("请单击确定按钮");
public static void main(String []args){
//JTextField txtA=new JTextField("请单击确定按钮");
... ...
public void actionPerformed(ActionEvent e){
JButton b=(JButton)e.getSource();
b.setText("OK");
txtA.setText("修改后的值");//在这里修改他的值。
}
------解决方案--------------------
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyTest_12{
public static void main(String []args){
JTextField txtA=new JTextField("请单击确定按钮");
JButton btOk=new JButton("确定");
ActionListener myal=new myActionListener(){
public void actionPerformed(ActionEvent e){
b.setText("OK");
}
};btOk.addActionListener(myal);
JPanel p=new JPanel();
p.add(txtA);
p.add(btOk);
JFrame f=new JFrame();
f.setSize(200,300);
Container contentPane=f.getContentPane();
contentPane.add(p);
f.show();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
改用匿名内部类,匿名内部类默认拥有外部类对象的引用,所以就可以访问外部类的成员变量