代码之家  ›  专栏  ›  技术社区  ›  razshan

如何驯服JOptionPane对话框中的X?

  •  2
  • razshan  · 技术社区  · 15 年前

    而且,现在每当我单击右上角的“X”按钮时,对话框的行为就像我单击了“确定”(消息)或“是”(问题)。当用户点击X时,我什么都不想做。

    int c =JOptionPane.showConfirmDialog(null, "Are you hungry?", "1", JOptionPane.YES_NO_OPTION);
    if(c==JOptionPane.YES_OPTION){
    JOptionPane.showMessageDialog(null, "eat!", "Order",JOptionPane.PLAIN_MESSAGE);
    }
    else {JOptionPane.showMessageDialog(null, "ok cool", "Order",JOptionPane.PLAIN_MESSAGE);} 
    
    2 回复  |  直到 15 年前
        1
  •  3
  •   robert_x44    15 年前

    已更改为显示如何根据问题的操作说明忽略对话框上的“取消”按钮:

    JOptionPane pane = new JOptionPane("Are you hungry?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
    
    JDialog dialog = pane.createDialog("Title");
    dialog.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent evt) {
        }
    });
    dialog.setContentPane(pane);
    dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    dialog.pack();
    
    dialog.setVisible(true);
    int c = ((Integer)pane.getValue()).intValue();
    
    if(c == JOptionPane.YES_OPTION) {
      JOptionPane.showMessageDialog(null, "eat!", "Order",JOptionPane.PLAIN_MESSAGE);
    }
    else if (c == JOptionPane.NO_OPTION) {
      JOptionPane.showMessageDialog(null, "ok cool", "Order",JOptionPane.PLAIN_MESSAGE);
    }
    
        2
  •  1
  •   Devon_C_Miller    15 年前

    你必须这样做:

    public static int showConfirmDialog(Component parentComponent,
        Object message, String title, int optionType)
    {
        JOptionPane pane = new JOptionPane(message, JOptionPane.QUESTION_MESSAGE,
            optionType);
        final JDialog dialog = pane.createDialog(parentComponent, title);
        dialog.setVisible(false) ;
        dialog.setLocationRelativeTo(parentComponent);
        dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        dialog.setModal(true);
        dialog.setVisible(true) ;
        dialog.dispose();
        Object o = pane.getValue();
        if (o instanceof Integer) {
            return (Integer)o;
        }
        return JOptionPane.CLOSED_OPTION;
    }
    

    dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);