JButton的动作侦听器无法正常工作 [英] Action Listener for JButton isn't working
本文介绍了JButton的动作侦听器无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试自己学习Java,并且正在寻找一个安全的文本编辑器,您必须登录该文本编辑器才能访问该文本。但是,动作侦听器无法使用任何按钮,而且我也无法弄清楚出了什么问题。
I'm trying to learn java by myself, and am looking to make a secure text editor that you have to log into to access the text. However, the action listener isn't working for any of the buttons, and i can't figure out what's wrong.
请注意,我之所以制作了两个按钮,仅仅是因为
Please note I've made two buttons only because the first didn't work.
我的代码如下:
public class storage extends JFrame{
private JTextField text1;
public JTextArea storearea;
public JButton newsave;
public JButton save;
public storage(UserProfile person) { //constructor with name passed in
super("Safe Storage");
setLayout(new FlowLayout());
JTextField text1 = new JTextField("Using program as: " + (person.getName()) );
text1.setEditable(false);
add(text1);
JTextArea storearea = new JTextArea(person.getText());
add(storearea);
JButton newsave = new JButton("Save");
add(newsave);
JButton save = new JButton("Save Changes");
add(save);
thehandler handler = new thehandler();
save.addActionListener(handler);
newsave.addActionListener(handler);
} //end constructor
public class thehandler implements ActionListener { //Handler
public void actionPerformed(ActionEvent event){
if(event.getSource() == save) {
System.out.println("Overwriting text");
}
else if(event.getSource() == newsave) {
System.out.println("Overwriting text new");
}
}
} //end thehandler
} //end class
推荐答案
您已声明实例变量(为空);
You have declared an instance variable (which is null);
public JButton newsave;
和一个局部变量:
JButton newsave = new JButton("Save");
您不希望局部变量(仅实例变量),因此代码应为:
You don't want the local variable (only the instance variable), so the code should be:
newsave = new JButton("Save");
这篇关于JButton的动作侦听器无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文