我正在创建一个需要一些简单输入的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);
}
}
答案 0 :(得分:9)
您需要像这样为按钮组件添加一个动作侦听器。
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();
}
答案 1 :(得分:5)
您必须将“addActionListener”添加到按钮
答案 2 :(得分:0)
你也可以使用@ 182Much的方法,如下所述:java detect clicked buttons 希望如果仍有疑虑,这会有所帮助。