问题
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.
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
回答1:
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");
来源:https://stackoverflow.com/questions/17757537/action-listener-for-jbutton-isnt-working