Java:actionPerformed方法在单击按钮时不触发

我正在创建一个需要一些简单输入的gui应用程序,但是,当我单击JFrame中的按钮时,我正在使用的actionPerformed方法没有被触发/触发(没有任何反应)。 我似乎无法弄清楚我错过了什么(如果有帮助,那就是java新手)。 感谢您的帮助/建议。

这是所有代码:

//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); } } 

您需要像这样向按钮组件添加动作侦听器。

 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(); } 

您必须在按钮中添加“addActionListener”

您也可以使用@ 182Much的方法,如下所述: java detect click click 按钮如果仍有疑虑,希望它有用。