我正在尝试获取传递给 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 Gray 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 弹出窗口。