创建自定义阻止Java Swing提示

Rei*_*vax 6 java swing jdialog blocking joptionpane

这个问题解决了.

我正在开发基于Java Swing的投影,并且应用程序的外观和感觉是完全自定义的.我们试图在整个程序中保持一致的外观,并且默认的Java对话框窗口不一样.

当前问题需要控制阻止对用户提示的调用.与JOptionPane.showConfirmDialog()类似,在这种情况下,静态调用会生成一个窗口,并停止程序流,直到用户选择一个选项.它还返回选项的值.请注意,GUI本身没有逻辑锁定,但用户无法与其余部分进行交互.

int n = JOptionPane.showConfirmDialog(this,
    "Are you sure?",
    "Confirm"
    JOptionPane.YES_NO_OPTION);
Run Code Online (Sandbox Code Playgroud)

我想使用自定义外观和使用字符串复制此功能.理想情况下,我的代码如下所示:

String result = CustomPrompt.showPrompt(this,
    "Please enter your name", //Text
    "Prompt.",                //Title
    "John Smith");            //Default
Run Code Online (Sandbox Code Playgroud)

这通常用于密码输入,我理解密码的返回类型不同,但这是一个例子.这可以通过在几个类中使用一系列按钮和事件监听器来完成,但代码的可读性和应用程序的可靠性会降低.

框架将通过NetBeans构建并从那里进行定制.我知道Swing中已存在这样的提示,但它的外观和感觉完全不同.

总结的问题是:如何使用自定义框架以阻止方式提示用户输入.

该问题的解决方案如下:

public class PromptForm extends JDialog
{
    transient char[] result;

    public char[] getResult()
    {
        return result;
    }
    public PromptForm(Frame parent)
    {
        super(parent, true);
        initComponents();
    }
    public void prompt()
    {
        this.setVisible(true);
    }
    public static char[] promptForPassword(Frame parent)
    {
        PromptForm pf = new PromptForm(parent);
        pf.prompt();
        return pf.getResult();
    }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
    {
        result = jPasswordField1.getPassword();
        setVisible(false);
        dispose();
    }
    private void initComponents() {...}

    private javax.swing.JButton jButton1;
    private javax.swing.JPasswordField jPasswordField1;
}
Run Code Online (Sandbox Code Playgroud)

被称为:

    char [] ret = PromptForm.promptForPassword(this);
    JOptionPane.showMessageDialog(this, new String(ret), "Neat", JOptionPane.QUESTION_MESSAGE);
Run Code Online (Sandbox Code Playgroud)

Ant*_*oly 5

Make CustomPrompt扩展JDialog,让它的构造函数调用super传递所有者Window和所需的ModalityType.

public class CustomPrompt extends JDialog {

  public static String showPrompt(Window parent, String title, String text, 
         String defaultText) {
    final CustomPrompt prompt = new CustomPrompt(parent);
    prompt.setTitle(title);
    // set other components text
    prompt.setVisible(true);

    return prompt.textField.getText();
  }

  private JTextField textField;

  // private if you only want this prompt to be accessible via constructor methods
  private CustomPrompt(Window parent) {
    super(parent, Dialog.DEFAULT_MODALITY_TYPE); 
    // Java >= 6, else user super(Frame, true) or super(Dialog, true);
    initComponents(); // like Netbeans
  }

  // initComponents() and irrelevant code. 
}
Run Code Online (Sandbox Code Playgroud)