package gui;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class OperateFrame {
JButton button_1,button_2;
JFrame frame;
JTextField tf;
JPanel p;
public OperateFrame() {
JFrame frame;
p=new JPanel();
frame = new JFrame("计算机");
frame.setBounds(100, 100, 450, 242);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(p);
Handle handle=new Handle();
tf = new JTextField(30);
tf.setBounds(10, 10, 299, 49);
p.add(tf);
tf.setColumns(10);
JButton button_1 = new JButton("1");
button_1.setBounds(10, 69, 93, 23);
button_1.addActionListener(handle);
p.add(button_1);
JButton button_2 = new JButton("2");
button_2.setBounds(113, 69, 93, 23);
button_2.addActionListener(handle);
p.add(button_2);
}
public static void main(String[] args) {
new OperateFrame();
}
//////////////以下是监听器的实现///////////////////
class Handle implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try{
System.out.println("22222");
System.out.println(e.getSource()==button_1); //这里每当按下按钮1都显示false
if(e.getSource()==button_1){
System.out.println("tttttt");
tf.setText(tf.getText()+"1");
System.out.println("wwwww");
}
else if (e.getSource()==button_2){
tf.setText(tf.getText()+"2");
}
}catch (Exception ex){
ex.printStackTrace();
}
}
}
}
以下是运行的截图,每次运行textField都无法输出文本,getSource()是false,请问是什么原因以及应该如何解决呢,求各位赐教
------解决思路----------------------
我来了
楼主你重复定义了
JButton button_1,button_2;你的这个类变量根本没有赋值
你又定义了2个局部变量 JButton button_1,button_2;
关键是局部变量在构造函数完成后消失了,木有直接引用啊,只有框架持有其隐式引用了~