简体   繁体   English

将actionlistener添加到joptionPane中的按钮(java)

[英]Add actionlistener to a button in joptionPane (java)

How can I add ActionListener to a JButton in JOptionPane . 如何在JOptionPane中将ActionListener添加到JButton中。 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");
    }
}); 

How can I add actionlistener to a button in joptionPane. 如何在joptionPane中的按钮上添加动作监听器。

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. 但是,您实际上并不想提供自己的自定义按钮,因为即使您添加ActionListener,您仍然需要自己管理对话框的关闭。

Instead a better solution is to just provide custom Strings and let the JOptionPane manage the buttons and closing of the dialog. 相反,更好的解决方案是仅提供自定义字符串,并让JOptionPane管理按钮和对话框的关闭。

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

Read the Swing tutorial on How to Make Dialogs for more information on using option panes. 阅读有关如何制作对话框的Swing教程, 获取有关使用选项窗格的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM