问题
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