views:

40

answers:

2

Also, right now whenever I click the 'X" button on top right, the dialog boxes behaves as if I clicked OK (on messages) or YES (on questions). When the user clicks the X, I want DO_Nothing.

In the code below, when i click on the X on the dialog box, it pops out the 'eat!'. Apparently, the X is acting as 'YES' Option, which it should not.

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  A: 

Changed to show how to ignore the cancel button on Dialog box per OP clarification of question:

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);
}
RD
Is there a way, even if I press X. Nothing will happen..Like handicap that particular actionListener.
Faraz Khan
Some line of code at the beginning of code that implements this "aight if anyone presses an X on the dialog boxes, nothings gonna happen, I want my user to complete the program!"
Faraz Khan
Thanks it works, I was wondering since the title menu is now pretty much useless, Is there a way to take it off. (hide the X, the title menu)
Faraz Khan
+1  A: 

You can't do what you want through the usual JOptionPane.show* methods.

You have to do something like this:

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;
}

The line that actually disables the close button is:

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