2013-08-23 139 views
7

我有我自己的對話框彈出兩個文本框,兩個JLabel和一個「確定」JButton。彈出窗口是一個登錄窗口。窗口完美工作我只是想知道我能夠添加一個「取消」JButton,所以用戶可以取消登錄。JOptionPane輸入用戶名和密碼

這裏是我的窗口代碼:

public Hashtable<String, String> login(JFrame frame) { 
    Hashtable<String, String> logininformation = new Hashtable<String, String>(); 

    JPanel panel = new JPanel(new BorderLayout(5, 5)); 

    JPanel label = new JPanel(new GridLayout(0, 1, 2, 2)); 
    label.add(new JLabel("E-Mail", SwingConstants.RIGHT)); 
    label.add(new JLabel("Password", SwingConstants.RIGHT)); 
    panel.add(label, BorderLayout.WEST); 

    JPanel controls = new JPanel(new GridLayout(0, 1, 2, 2)); 
    JTextField username = new JTextField(); 
    controls.add(username); 
    JPasswordField password = new JPasswordField(); 
    controls.add(password); 
    panel.add(controls, BorderLayout.CENTER); 

    JOptionPane.showMessageDialog(frame, panel, "login", JOptionPane.QUESTION_MESSAGE); 

    logininformation.put("user", username.getText()); 
    logininformation.put("pass", new String(password.getPassword())); 
    return logininformation; 
} 

如果你需要它,這裏是登錄窗口的截圖:

Login pop up

,如果您點擊「X 「在右角,它也會關閉。但是我想要取消JButton,如果這很容易。

  • 謝謝大家幫忙

回答

6

你需要使用一個OKCANCEL型確認對話框。

JOptionPane.showConfirmDialog(
      frame, panel, "login", JOptionPane.OK_CANCEL_OPTION); 
+0

這是我的答案^^非常感謝! – Gerret

+1

不客氣。 +1也給你。 –

0

您可以使用JFrame的dispose()功能關閉幀當你點擊的按鈕。像這樣

jButton1.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e){ 
     frameName.dispose(); 
    } 
}); 
+0

是的,這是一個好的開始,但我有更多的問題,我不能添加一個secound按鈕和/或不知道在哪裏! – Gerret

0

您需要使用JOptionPage.showOptionDialog()使添加按鈕

+0

好的是可以理解的,但我有問題,我不知道我必須填寫messageType,icon,options和initialValue ...你能幫我嗎? – Gerret

+0

messageType可以是'ERROR_MESSAGE,INFORMATION_MESSAGE,WARNING_MESSAGE,QUESTION_MESSAGE或PLAIN_MESSAGE'中的任何一個,剩下的就可以傳遞'null'。您可以參考文檔以獲取更多信息 –

+0

...嗯,我不明白它通過null沒有問題,但我有一個OptionType和MessageType有什麼區別?在我的代碼中,我在OptionType中使用了'QUESTION_MESSAGE'。所以在OptionType ... – Gerret

相關問題