2016-11-26 107 views
3

我正在創建一個簡單的選項窗格,要求輸入多個用戶。我已經指定了標籤和文本字段,但是在我的選項窗格末尾有一個不屬於任何變量的文本字段,所以我猜測它在指定選項窗格時會出現。如何擺脫JOptionPane.showInputDialog中的默認文本字段?

這裏是我的代碼:

JTextField locationField = new JTextField(10); 
    JTextField usedByField = new JTextField(5); 
    JTextField commentField = new JTextField(50); 

    ... 

    myPanel.add(new JLabel("Location: "); 
    myPanel.add(locationField); 

    myPanel.add(new JLabel("Used By: "); 
    myPanel.add(usedByField); 

    myPanel.add(new JLabel("Comments: "); 
    myPanel.add(commentField); 

    ... 

    JOptionPane.showInputDialog(myPanel); 

我的對話結束了看起來像這一點,你可以看到有一個流浪的文本字段我窗格底部:

​​

我的問題是,在我的代碼中,我會祕密地指定這個嗎?我不認爲我是,所以我怎麼去解決這個我不需要的流浪文本字段。

謝謝。

回答

4

解決方法很簡單:不要使用JOptionPane.showInputDialog(...)。請使用JOptionPane.showMessageDialog(...)

showInputDialog構建爲從用戶獲取單個字符串輸入,因此它被構造爲顯示一個嵌入的JTextField用於此目的,並返回輸入到該字段中的字符串,這是您不使用的字符串。

另一方面,showMessageDialog不執行此操作,而是根據按鈕的哪個按鈕被按下而返回int。

請查看JOptionPane API瞭解更多。

編輯:我錯了。如果您希望對話框提供對話框處理按鈕,如「確定」,「取消」或「是」和「否」,並允許用戶按下這些按鈕,然後從按鈕獲得輸入,請使用JOptionPane.showConfirmDialog(...)

例如:

final JTextField userNameField = new JTextField(10); 
final JPasswordField passwordField = new JPasswordField(10); 
JPanel pane = new JPanel(new GridBagLayout()); 
GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, 
     GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, 
     new Insets(2, 2, 2, 2), 0, 0); 
pane.add(new JLabel("User Name:"), gbc); 

gbc.gridy = 1; 
pane.add(new JLabel("Password:"), gbc); 

gbc.gridx = 1; 
gbc.gridy = 0; 
gbc.anchor = GridBagConstraints.EAST; 
pane.add(userNameField, gbc); 

gbc.gridy = 1; 
pane.add(passwordField, gbc); 

int reply = JOptionPane.showConfirmDialog(null, pane, "Please Log-In", 
     JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); 
if (reply == JOptionPane.OK_OPTION) { 
    // get user input 
    String userName = userNameField.getText(); 

    // ****** WARNING ****** 
    // ** The line below is unsafe code and makes a password potentially discoverable 
    String password = new String(passwordField.getPassword()); 

    System.out.println("user name: " + userName); 
    System.out.println("passowrd: " + password); 
} 

其中顯示:

enter image description here

+0

真棒,太感謝你了。我會更多地關注它,但現在它正在按照我的期望工作。 – juiceb0xk

+0

@ juiceb0xk:非常歡迎你,祝你好運! –

+0

@ juiceb0xk:我錯了。請參閱編輯。 –