您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

我仅从以下对象得到null:对象selectedValue = jPane.getValue(); (jPane =新的JOptionPane(...)

我仅从以下对象得到null:对象selectedValue = jPane.getValue(); (jPane =新的JOptionPane(...)

如果将JButtons选项作为放入JOptionPane,则需要指定单击它们时发生的情况。由于您似乎没有任何按钮ActionActionListener绑定到按钮,因此什么也没有发生。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class JOptionPaneTest {

    public void createAndShowJOptionPane() {
        final JButton b1 = new JButton("Yes, please");
        b1.setName("yes_please");
        final JButton b2 = new JButton("No, thx");
        b2.setName("no_thx");
        final JButton b3 = new JButton("Leave me alone");
        b3.setName("leave_me_alone");
        Object[] options = new Object[]{b1, b2, b3};

        final JOptionPane optionPane = new JOptionPane("Message", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION, null, options, options[2]);
        final JDialog dialog = optionPane.createDialog("Title");
        b1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println(b1.getText());
                optionPane.setValue(0);
                dialog.dispose();
            }
        });
        b2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println(b2.getText());
                optionPane.setValue(1);
                dialog.dispose();
            }
        });
        b3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println(b3.getText());
                optionPane.setValue(2);
                dialog.dispose();
            }
        });
        dialog.setVisible(true);

        if ((Integer)optionPane.getValue() == 0) {
            System.out.println("Woohoo!");
        }
    }

    public static void main(String[] argv) {
        SwingUtilities.invokelater(new Runnable() {
            public void run() {
                JOptionPaneTest test = new JOptionPanetest();
                test.createAndShowJOptionPane();
            }
        });
    }
}
其他 2022/1/1 18:35:12 有439人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶