Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: actionPerformed method not firing when button clicked

I'm creating a gui application that requires some simple input, however, when I click the button in the JFrame the actionPerformed method I'm using is not fired/firing (nothing happens). I can't seem to figure out what I've missed (new to java if that helps). thanks for any help/advice.

Here is all the code:

//gui class
public class guiUser extends JFrame implements ActionListener {

private JButton buttonClose_;
private final int frameWidth = 288;
private final int frameHeight = 263;
private final int closeX = 188;
private final int closeY = 195;
private final int closeWidth = 75;
private final int closeHeight = 25;

public guiUser() {

    setTitle("Create a User");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(null);
    setSize(frameWidth, frameHeight);
    setResizable(false);

    buttonClose_ = new JButton("Exit");
    buttonClose_.setLayout(null);
    buttonClose_.setSize(closeWidth, closeHeight);
    buttonClose_.setBounds(closeX, closeY, closeWidth, closeHeight);
    buttonClose_.setLocation(closeX, closeY);
    add(buttonClose_);

}

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource() == buttonClose_) {
        int result = JOptionPane.showConfirmDialog(null, "Are you sure you wish to exit       user creation?");
        if(result == JOptionPane.YES_OPTION) {
            System.exit(0);
        } 
    }
}

//tests the gui
public class test {
    public static void main(String args[]) {
        guiUser gUser_ = new guiUser();
        gUser_.setVisible(true);
    }
}
like image 468
Ari Avatar asked Dec 10 '22 03:12

Ari


2 Answers

You need to add an action listener to your button component like this.

closeButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        closeButtonActionPerformed(evt);
    }
});

private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {
    dispose();
}
like image 167
Logan Avatar answered Dec 11 '22 17:12

Logan


You must add an "addActionListener to your button

like image 28
Digitaldax Avatar answered Dec 11 '22 15:12

Digitaldax