2013-03-24 76 views
0

所以,我創建了一個簡單的對話框來獲取用戶輸入,但文本字段顯示兩次。這是一個SSCCE。文本字段在JOptionPane.showInputDialog中顯示兩次。爲什麼?

public static void main(String[] args) { 
    JTextField fileName = new JTextField(); 
    Object[] message = {"File name", fileName}; 
    String option = JOptionPane.showInputDialog(null, message, "Add New", JOptionPane.OK_CANCEL_OPTION); 
    System.out.println(fileName.getText()); 
} 

enter image description here

有什麼不對這裏的代碼?

回答

4

它這樣做是因爲您在message[]中也添加了JTextField對象。

Object[] message = {"File name", fileName};//sending filename as message

因此,所示的第一JTextField是使用inputdialog固有之一,另外一個是你自己JTextField您要發送的消息。

我猜想是你想發送fileName的內容給消息。在這種情況下,你的代碼應該是這樣的:

public static void main(String[] args) { 
    JTextField fileName = new JTextField(); 
    Object[] message = {"File name", fileName.getText()};//send text of filename 
    String option = JOptionPane.showInputDialog(null, message, "Add New", JOptionPane.OK_CANCEL_OPTION); 
    System.out.println(fileName.getText()); 
} 

UPDATE
如果你想只取輸入,則沒有必要發送對象filename的消息。您應該簡單地按照以下步驟操作:

public static void main(String[] args) { 
     //JTextField fileName = new JTextField(); 
     Object[] message = {"File name"}; 
     String option = JOptionPane.showInputDialog(null, message, "Add New", JOptionPane.OK_CANCEL_OPTION); 
     if (option == null) 
     System.out.println("Cancell is clicked.."); 
     else 
     System.out.println(option+ " is entered by user"); 
    } 
+0

其實,我想從用戶的輸入。但是這解釋了。 – 2013-03-24 15:36:59

+0

如果你只想使用輸入,那麼不要發送'filename'作爲消息。「JOptionPane.inputDialog」會自動爲你做。 – 2013-03-24 15:39:08

+0

那麼如何檢查用戶是否點擊確定或取消? – 2013-03-24 15:54:34

2

默認情況下,輸入對話框包含文本字段,因此您不需要添加另一個對話框。嘗試也許這種方式

String name = JOptionPane.showInputDialog(null, "File name", 
     "Add New", JOptionPane.OK_CANCEL_OPTION); 
System.out.println(name); 
+0

那麼如何檢查用戶是否點擊確定或取消? – 2013-03-24 15:51:14

+0

@ user2059238如果用戶單擊Cancel'name'將爲'null'。如果用戶點擊確定而不輸入任何內容,你可以用'if(name == null)'或者更好的if(name == null || name.isEmpty())'來測試。 – Pshemo 2013-03-24 15:55:00

相關問題