我试图获取传递给JOptionPane的自定义按钮返回的值。然而,我传递的按钮根本不返回任何值。只有当按下退出按钮时,才会返回-1的值。我需要这个值,因为我正在更改启用或禁用按钮的属性。我认为我需要让按钮以某种方式向JOptionPane返回一些信息。有什么建议吗?
JButton button1= new JButton("Button 1");
JButton button2= new JButton("Button 2");
button1.setEnabled(false);
int value = JOptionPane.showOptionDialog(null, "Heres a test message", "Test", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{button1, button2}, button1);
JOptionPane.showMessageDialog(null, "You entered " + value);
注:这与我之前的问题有关 - JOptionPane Grey Out One Button
我尝试按照您说的设置按钮的值,但它们从未返回“OK”或“CANCEL”。
每当检查按钮的值时,它们从未返回我设置的值。
JButton button1= new JButton("Button1");
JButton button2= new JButton("Button2");
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
// set the value of the option pane
pane.setValue(JOptionPane.OK_OPTION);
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane pane = getOptionPane((JComponent)e.getSource());
// set the value of the option pane
pane.setValue(JOptionPane.CANCEL_OPTION);
}
});
if (JOptionPane.showOptionDialog(null, "Pick a button", "Pick", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{button1, button2}, button1) == JOptionPane.OK_OPTION) {
JOptionPane.showMessageDialog(null, "Button1");
}
else{
JOptionPane.showMessageDialog(null, "Button2");
}
请参考上面的内容,无论什么情况下我都会得到button2弹出窗口。