Java:actionPerformed方法在单击按钮时不触发 [英] Java: actionPerformed method not firing when button clicked

查看:1233
本文介绍了Java:actionPerformed方法在单击按钮时不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

以下是所有代码:

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


推荐答案

你需要像这样向你的按钮组件添加一个动作监听器。

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

这篇关于Java:actionPerformed方法在单击按钮时不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆