[英]Action Listener for JButton isn't working
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. 我正在尝试自己学习Java,并希望制作一个安全的文本编辑器,您必须登录才能访问该文本。 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. 请注意,我之所以做出了两个按钮,仅仅是因为第一个按钮不起作用。
My code is below: 我的代码如下:
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;
and a local variable: 和一个局部变量:
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.