JDialog 框对是和否给出相同的结果 buttons/inputs

JDialog box giving same result for both yes and no buttons/inputs

我创建了一个 JDialog 框来向用户显示一些警告消息。当用户收到警告消息时,如果他点击是按钮,应用程序会做一些工作,如果用户选择否,那么他会留在同一个地方。 我得到 0 值表示是,1 值表示否。但是 JDialog 框对是和否按钮给出相同的结果,即应用程序正在关闭两个输入。但我想要的是,如果用户选择是,那么应用程序会做一些事情,如果他选择否,那么什么也不会发生(UI window 保持打开状态)。

public void warningMassage(String Text) {
    int n = JOptionPane.showConfirmDialog(frame, Text, "Warning", JOptionPane.YES_NO_OPTION);
    System.out.println(n);
    if(n == 0){
        System.exit(0);
        System.out.println(JOptionPane.YES_OPTION);
    } else {
        frame.setVisible(true);
    }
}//warningMassage

使用

if(n==JOptionPane.YES_OPTION)
    //yes pressed
else
    //no pressed

JOptionPane.showConfirmDialog()JOptionPane.YES_NO_OPTION 可以 return:

  • JOptionPane.YES_OPTION: public static final int YES_OPTION = 0;
  • JOptionPane.NO_OPTION: public static final int NO_OPTION = 1;

您应该在检查中使用这些常量:

if (JOptionPane.showConfirmDialog(...) == JOptionPane.YES_OPTION) {
    // do something
}

但是,一个小提示:如果你想显示一个警告信息,考虑使用这个:

JOptionPane.showConfirmDialog(
    parentComponent,
    message,
    title,
    optionType,
    messageType
);

其中 messageType 是一个整数,用于指定消息的类型;主要用于从可插入的外观中确定图标:ERROR_MESSAGEINFORMATION_MESSAGE WARNING_MESSAGEQUESTION_MESSAGEPLAIN_MESSAGE.

那么,在你的情况下:

JOptionPane.showConfirmDialog(
    null,
    "message",
    "TITLE",
    JOptionPane.YES_NO_OPTION,
    JOptionPane.WARNING_MESSAGE// <--- !!
);

使用下面的代码

public void warningMassage(String yourText){
    int n = JOptionPane.showConfirmDialog(
            frame,
            yourText,
            "Warning",
            JOptionPane.YES_NO_OPTION);
    System.out.println(n);
      if(n == JOptionPane.YES_OPTION){
          frame.setVisible(true);
      }
      else{
          System.exit(0);
          System.out.println(JOptionPane.YES_OPTION);
      }
}//warningMassage

一个是 returns 0 和一个否 returns 1

Documentation for the JDialog Box

JDialog box notyesno 输入给出相同的结果 .如果您选择 No 框架不会关闭,直到您按下

终端 或者您明确设置

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

正如@Cool Guy所说,我也更喜欢使用

if(n==JOptionPane.YES_OPTION)
    //yes pressed
else
    //no pressed

但目前你的问题不是这个。Do Post your Main Class