Action Listener for JButton isn't working

巧了我就是萌 提交于 2020-01-07 03:38:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!