JOptionPane是或否窗口
我正在尝试使用“是”或“否”按钮创建消息。 然后会出现一个窗口,其中包含某条消息,该消息取决于用户是单击是还是否。
这是我的代码:
public class test{ public static void main(String[] args){ //default icon, custom title int n = JOptionPane.showConfirmDialog( null, "Would you like green eggs and ham?", "An Inane Question", JOptionPane.YES_NO_OPTION); if(true){ JOptionPane.showMessageDialog(null, "HELLO"); } else { JOptionPane.showMessageDialog(null, "GOODBYE"); } System.exit(0); } }
现在无论是否按下是或否,它都打印HELLO。当用户选择否时,如何让它显示GOODBYE?
“如果(真实)”将永远是真的,它永远不会成为其他人。 如果您希望它正常工作,您必须这样做:
int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION); if (reply == JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog(null, "HELLO"); } else { JOptionPane.showMessageDialog(null, "GOODBYE"); System.exit(0); }
您总是在检查真实情况,因此您的信息将始终显示。
你应该用if ( n == JOptionPane.YES_OPTION)
替换你的if (true)
语句
当其中一个showXxxDialog方法返回一个整数时,可能的值为:
YES_OPTION NO_OPTION CANCEL_OPTION OK_OPTION CLOSED_OPTION
从这里开始
你可以解决这个问题:
if(n == JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog(null, "HELLO"); } else { JOptionPane.showMessageDialog(null, "GOODBYE"); }
你可以更简单地做到这一点:
int test = JOptionPane.showConfirmDialog(null, "Would you like green eggs and ham?", "An insane question!"); switch(test) { case 0: JOptionPane.showMessageDialog(null, "HELLO!"); //Yes option case 1: JOptionPane.showMessageDialog(null, "GOODBYE!"); //No option case 2: JOptionPane.showMessageDialog(null, "GOODBYE!"); //Cancel option }
您正在写if(true)
所以它将始终显示“Hello”消息。
您应该根据返回的n
值做出决定。
代码为是和否消息
int n = JOptionPane.showConfirmDialog( null, "sample question?!" , "", JOptionPane.YES_NO_OPTION); if(n == JOptionPane.YES_OPTION) { JOptionPane.showMessageDialog(null, "Opening..."); } else { JOptionPane.showMessageDialog(null, "Goodbye"); System.exit(0);
沿着这些方向……
//default icon, custom title int n = JOptionPane.showConfirmDialog(null,"Would you like green eggs and ham?","An Inane Question",JOptionPane.YES_NO_OPTION); String result = "?"; switch (n) { case JOptionPane.YES_OPTION: result = "YES"; break; case JOptionPane.NO_OPTION: result = "NO"; break; default: ; } System.out.println("Replace? " + result);
您可能还想查看DialogDemo