Java: actionPerformed method does not work when a button is clicked

I am creating a gui application that requires simple input, however, when I click the button in the JFrame, the actionPerformed method that I use does not start / does not start (nothing happens). I can't figure out what I missed (new to java if that helps). Thanks for any help / advice.

Here is the whole 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); } } 
+4
source share
3 answers

You need to add an action listener to the component of your button 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(); } 
+9
source

You must add "addActionListener" to your button

+5
source

You can also use the @ 182Much method, as discussed here: java detect clicked buttons Hope this will be useful if there are still problems.

0
source

Source: https://habr.com/ru/post/1389184/


All Articles