繁体   English   中英

JOptionPane 并从输入中获取文本

[英]JOptionPane and getting text from input

我创建了一个打开JOptionPane的按钮。 它允许用户输入一个string..>> String str = JOptionPane.showInputDialog如何获取用户输入到 joptionpane 的文本并使用它来搜索用户对象?

非常感谢

返回的字符串是用户输入的字符串,如果用户选择取消,则返回null:

String whatTheUserEntered = JOptionPane.showInputDialog(...);
if (whatTheUserEntered == null) {
    System.out.println("The user canceled");
}

尽管@JB Nizet已经给出了很好的答案。 如果有人再次寻找此问题,我想添加一个简短的代码示例,以供参考。

public class JOptionPaneExample

{私人双倍价格;

private JTextField priceField;

private JLabel priceLabel;

public JOptionPaneExample()
{
    priceField = new JTextField(10);
}

public void createAndDisplayGUI()
{
    int selection = JOptionPane.showConfirmDialog(null, getPanel(), "Price Form : ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

    if (selection == JOptionPane.OK_OPTION)
    {
        price = Double.valueOf(priceField.getText());

        JOptionPane.showMessageDialog(null, "Price is : " + Double.toString(price), "Price : ", JOptionPane.PLAIN_MESSAGE);
    }
    else if (selection == JOptionPane.CANCEL_OPTION)
    {
        // Do something here.
    }
}

private JPanel getPanel()
{
    JPanel basePanel = new JPanel();
    basePanel.setOpaque(true);
    basePanel.setBackground(Color.BLUE.darker());

    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new GridLayout(3, 2, 5, 5));
    centerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    centerPanel.setOpaque(true);
    centerPanel.setBackground(Color.WHITE);

    priceLabel = new JLabel("Enter Price : ");

    centerPanel.add(priceLabel);
    centerPanel.add(priceField);

    basePanel.add(centerPanel);

    return basePanel;
}

}

可以在此博客中找到相同的代码

我在源代码中找到了一些有用的JOptionPane示例。 我想它会帮助你...

链接: Java JOptionPane

您的目的还不清楚,但是根据我的了解,您只是想知道如何输入信息,这可以通过简单地调用变量来完成。

要查看变量中包含什么,请使用System.out.println(变量名);

请定义用户对象?

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM