import javax.swing.JFrame;
import javax.swing.JTextField;
public class Frame1 extends JFrame {
public static JTextField tf;
public Frame1() {
tf = new JTextField();
add(tf);
setSize(200, 100);
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Frame2 extends JFrame {
private JButton button;
public Frame2(){
button = new JButton("触发");
add(button);
setSize(50, 50);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Frame1.tf.setText("事件触发,改变JTextField的值");
}
});
}
}
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Frame1 f1 = new Frame1();
Frame2 f2 = new Frame2();
f1.setVisible(true);
f2.setVisible(true);
}
}
设置成public的,并把JTextField的实例放在一个公共的上下文中,设置成静态变量。