如何处理JOptionPane.showConfirmDialog中的选项类型

时间:2012-03-14 15:28:14

标签: java swing jdialog joptionpane

当点击JOptionPane中的按钮时,我需要一种编写一些代码来处理事件的方法。我实际上正在使用JOptionPane插入用户名和密码,如果单击正确和确定按钮,JOptionPane将消失,父JFrame保持活动状态,如果单击取消按钮,程序将退出。我的示例代码仅显示JOptionpane并单击任何按钮才会关闭它 `JPanel panel = new JPanel();         panel.setLayout(new GridLayout(4,1));         //创建带文本的标签(用户名)         JLabel用户名=新JLabel(“用户名”);

    //Create a label with text (Password)
    JLabel password = new JLabel("Password");

    //Create text field that will use to enter username
    JTextField textField = new JTextField(12);

    //Create password field that will be use to enter password
    JPasswordField passwordField = new JPasswordField(12);

    //Add label with text (username) into created panel
    panel.add(username);

    //Add text field into created panel
    panel.add(textField);

    //Add label with text (password) into created panel
    panel.add(password);

    //Add password field into created panel
    panel.add(passwordField);

    //Show JOptionPane that will ask user for username and password
    JOptionPane.showConfirmDialog(mainFrame, panel, "Enter username and password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);`

2 个答案:

答案 0 :(得分:4)

这些对话框返回int值,该值可解释为以下值之一:

  • YES_OPTION
  • NO_OPTION
  • CANCEL_OPTION
  • OK_OPTION
  • CLOSED_OPTION

例如,

final int option = JOptionPane.showConfirmDialog(mainFrame, panel, "Enter username and password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
if(option == JOptionPane.OK_OPTION){
    // OK was pressed. Now do stuff.
}
else if(option == JOptionPane.CANCEL_OPTION){
    // Cancel was pressed. Now do stuff.
}

答案 1 :(得分:2)

Javadoc救援:

  

返回:

     

指示用户选择的选项的int

将结果与JOptionPane(OK_OPTIONCANCEL_OPTIONCLOSED_OPTION等中定义的常量进行比较。