将actionlistener添加到joptionPane中的按钮(java) [英] Add actionlistener to a button in joptionPane (java)

查看:84
本文介绍了将actionlistener添加到joptionPane中的按钮(java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将ActionListener添加到JOptionPane中的JButton.这样,当我按下按钮时,它将执行某些代码. 我尝试使用此代码,但无法正常工作:

How can I add ActionListener to a JButton in JOptionPane. So that when I press on the button, it excutes a certain code. I tried to use this code, but it is not working:

JButton button1= new JButton("Button 1");
int value = JOptionPane.showOptionDialog(null, "Here's a test message", "Test", JOptionPane.YES_OPTION , JOptionPane.QUESTION_MESSAGE, null,new Object[]{button1}, button1);
button1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        //code to excute
        System.out.println("code excuted");
    }
}); 

推荐答案

如何在joptionPane中的按钮上添加动作监听器.

How can I add actionlistener to a button in joptionPane.

好吧,您需要在显示选项窗格之前将ActionListener添加到按钮上.

Well, you need to add the ActionListener to the button BEFORE displaying the option pane.

但是,您实际上并不想提供自己的自定义按钮,因为即使添加了ActionListener,您仍然需要自己管理对话框的关闭.

However, you don't really want to do provide your own custom buttons because even if you add the ActionListener you will still need to manage the closing of the dialog yourself.

相反,更好的解决方案是仅提供自定义字符串,并让JOptionPane管理按钮和对话框的关闭.

Instead a better solution is to just provide custom Strings and let the JOptionPane manage the buttons and closing of the dialog.

然后您测试返回值并根据该值进行处理:

Then you test the return value and do you processing based on that value:

if (value == 0) // the string text you specify for the button
    // do something

如何制作对话框上阅读Swing教程有关使用选项窗格的更多信息.

Read the Swing tutorial on How to Make Dialogs for more information on using option panes.

这篇关于将actionlistener添加到joptionPane中的按钮(java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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