JButton 不能被禁用

乌古尔·希迪尔

我有一个 JButton,我希望在按下 10 次后将其禁用。尽管由于某种原因,我的代码不起作用。你能帮我解决这个问题吗?

button.addActionListener(new ActionListener() {
    int counter = 0;
    public void actionPerformed(ActionEvent arg0)
    {
        liste.add((double) Integer.parseInt(textField.getText()));
        textField.setText("");
        while(counter < 9)
        {
            counter++;

            if(counter == 10)
            {
                buton.setEnabled(false);
            }
        }
    }
}

另外,我想在按下 10 次时显示一个消息对话框。你能帮助我吗?

约翰内斯

您甚至不需要 while 循环,只需将 移动到int counter = 0上方addActionListener(...,并在public void actionPerformed(). 然后检查if (counter == 10)里面的actionPerformed。

要显示消息框,请使用 JOptionPane.showMessageDialog();

Javadoc

public static void showMessageDialog(Component parentComponent, 
    Object message, 
    String title, 
    int messageType)
    抛出 HeadlessException

调出一个对话框,该对话框使用由 messageType 参数确定的默认图标显示消息。


如果您正确执行,这大致就是您的代码最终应该是什么样子。

int counter = 0;

button.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        counter++;

        if(counter == 10)
        {
            button.setEnabled(false);

            // Show message dialog
            JOptionPane.showMessageDialog(null, "This is my message", "This is my message title", JOptionPane.INFORMATION_MESSAGE);
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章