JOptionPane Passing Custom Buttons

后端 未结 3 1357
陌清茗
陌清茗 2020-12-02 00:38

I\'m trying to get the value returned by custom buttons passed to JOptionPane. However the buttons I pass don\'t return a value at all. Only when the exit button is pressed

3条回答
  •  一整个雨季
    2020-12-02 01:33

    If you need this complex behavior, consider creating your own JDialog and then displaying it in a modal fashion.

    If you have to use a JOptionPane, you can do this by extracting its JDialog and recursively iterating through its components til you find the one you want to disable and disable it:

    import java.awt.Component;
    import java.awt.Container;
    import javax.swing.*;
    
    public class Foo2 {
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                doRun();
             }
          });
       }
    
       public static void doRun() {
          String[] options = {"Button 1", "Button 2", "Button 3"};
    
          JOptionPane myOptionPane = new JOptionPane("Heres a test message",
                JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, 
                null, options, options[2]);
          JDialog myDialog = myOptionPane.createDialog(null, "My Test");
          myDialog.setModal(true);
    
          inactivateOption(myDialog, options[1]);
    
          myDialog.setVisible(true);
          Object result = myOptionPane.getValue();
          // Note: result might be null if the option is cancelled
          System.out.println("result: " + result);
    
          System.exit(0); // to stop Swing event thread
       }
    
       private static void inactivateOption(Container container, String text) {
          Component[] comps = container.getComponents();
          for (Component comp : comps) {
             if (comp instanceof AbstractButton) {
                AbstractButton btn = (AbstractButton) comp;
                if (btn.getActionCommand().equals(text)) {
                   btn.setEnabled(false);
                   return;
                }
             } else if (comp instanceof Container) {
                inactivateOption((Container) comp, text);
             }
          }
    
       }
    }
    

    However for myself, I'd just create a JDialog.

提交回复
热议问题