用于请求数据的 Java 弹出窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6446881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:00:32  来源:igfitidea点击:

Java Pop-Up Window to Ask for Data

javauser-interfacepopup

提问by Philip McQuitty

What code would I use to ask a user to enter their grade into a pop-up window?

我将使用什么代码来要求用户在弹出窗口中输入他们的成绩?

When a JButton is pressed, I want a little box to pop-up and prompt the user to enter their grade. Furthermore, would it be possible to get the value of the entered double value?

当按下 JButton 时,我希望弹出一个小框并提示用户输入他们的成绩。此外,是否有可能获得输入的 double 值的值?

Thanks for all your time. I appreciate it!

感谢您的所有时间。我很感激!

回答by G__

You want a JOptionPane. Use something like the following code snippet inside the JButton's ActionListener:

你想要一个 JOptionPane。在 JButton 的 ActionListener 中使用类似于以下代码片段的内容:

            JTextArea textArea = new JTextArea();
            textArea.setEditable(true);
            JScrollPane scrollPane = new JScrollPane(textArea);
            scrollPane.requestFocus();
            textArea.requestFocusInWindow();
            scrollPane.setPreferredSize(new Dimension(800, 600));
            JOptionPane.showMessageDialog(
                    (ControlWindow) App.controller.control, scrollPane,
                    "Paste Info", JOptionPane.PLAIN_MESSAGE);
            String info = textArea.getText();

You could parse/validate the double value from the output string. You could also use different swing components - this example is a scrollable text area.

您可以解析/验证输出字符串中的双精度值。您还可以使用不同的摆动组件 - 此示例是一个可滚动的文本区域。

回答by whirlwin

The simplest approach would perhaps be to use JoptionPane.showInputDialog(...). However, be aware that it will crash if someone tries to enter anything other than a double.

最简单的方法可能是使用JoptionPane.showInputDialog(...). 但是,请注意,如果有人尝试输入双倍以外的任何内容,它会崩溃。

@Override
public void actionPerformed(ActionEvent actionEvent) {
    double someNumber = Double.parseDouble(
            JOptionPane.showInputDialog(this, "Type in grade:"));
}