Add actionlistener to a button in joptionPane (java)

情到浓时终转凉″ 提交于 2020-01-07 03:04:10

问题


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

回答1:


How can I add actionlistener to a button in joptionPane.

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

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.

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

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



来源:https://stackoverflow.com/questions/34487105/add-actionlistener-to-a-button-in-joptionpane-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!