2014-07-26 42 views
1

如果我沒有鍵入任何東西,無論按什麼按鈕(ok,cancel或x按鈕(右上角的按鈕),我的JOptionPane 都面臨一個問題在JOptionPane中)),它會提示我,直到我鍵入一個正值。但我只想在我按下OK時發生提示。JOptionPane處理好,取消和x按鈕

如果我點擊取消或X按鈕(在JOptionPane的右上方按鈕),它將關閉的JOptionPane

我怎樣才能做到這一點?

import javax.swing.JOptionPane; 

public class OptionPane { 
    public static void main(final String[] args) { 
     int value = 0; 
     boolean isPositive = false , isNumeric = true; 
     do { 
      try { 
       value = Integer.parseInt(JOptionPane.showInputDialog(null, 
        "Enter value?", null)); 
      } catch (NumberFormatException e) { 
       System.out.println("*** Please enter an integer ***"); 
       isNumeric = false; 
      } 

      if(isNumeric) { 
       if(value <= 0) { 
        System.out.println("value cannot be 0 or negative"); 
       } 

       else { 
        System.out.println("value is positive"); 
        isPositive = true; 
       } 
      } 
     }while(!isPositive); 
    } 
} 
+0

一旦取消或x按鈕被按下,您是否想要關閉pupup? – Braj

+0

@Braj是的,我想要關閉彈出一旦取消或x按鈕被按下。我的意思是,如果我沒有輸入任何值,JoptionPane會一直彈出,單擊取消,確定或x按鈕 – user3879568

+0

,所以您的意思是彈出,直到輸入任何正值,無論何處都可以,取消和x按鈕被點擊? – Braj

回答

3

這種情況的基本方法可以像我下面表明:

@MadProgrammer評論後更新。

import javax.swing.JFrame; 
import javax.swing.JOptionPane; 

public class DemoJOption { 
    public static void main(String args[]) { 
     int n = JOptionPane.showOptionDialog(new JFrame(), "Message", 
     "Title", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, 
     null, new Object[] {"Yes", "No"}, JOptionPane.YES_OPTION); 

     if (n == JOptionPane.YES_OPTION) { 
      System.out.println("Yes"); 
     } else if (n == JOptionPane.NO_OPTION) { 
      System.out.println("No"); 
     } else if (n == JOptionPane.CLOSED_OPTION) { 
      System.out.println("Closed by hitting the cross"); 
     } 
    } 
} 
+2

不是'JOptionPane.showOptionPane'返回一個表示用戶選擇的選項的整數,或者如果用戶關閉了對話框,這意味着'n == 0'返回CLOSED_OPTION。會更準確,因爲'JOptionPane.YES_OPTION'可以被定義爲任何東西......? – MadProgrammer

+0

你說得對。謝謝。 – bluevoxel

+0

不,不依賴於JOptionPane的常量,你不知道它們設置了什麼值,它們可以在JVM的實現/版本之間進行更改,這就是要點。相反,你應該使用0或1,它表示已知的選項數組的索引值... – MadProgrammer

1

只需將代碼中try塊,也沒有必要使用任何標誌只是break無限循環一旦進入正數。

示例代碼:

public static void main(final String[] args) { 
    int value = 0; 
    while (true) { 
     try { 
      value = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter value?", null)); 

      if (value <= 0) { 
       System.out.println("value cannot be 0 or negative"); 
      } else { 
       System.out.println("value is positive"); 
       break; 
      } 
     } catch (NumberFormatException e) { 
      System.out.println("*** Please enter an integer ***"); 
     } 
    } 
} 
1
JoptionPane#showInputDialog returns user's input, or null meaning the user canceled the input. 

因此而不是直接解析返回值。首先檢查它是否爲空(用戶已取消),然後不做任何事情,如果不爲空然後解析整數值

相關問題