java 如何在 GUI 中接受用户输入?- 爪哇

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28017323/
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-11-02 12:50:18  来源:igfitidea点击:

How to accept user input in GUI? - Java

javaswing

提问by Itheyln

My program takes an input amount of money and converts it into coins. I need it to have a GUI, and have to make it possible to enter the amount while in the GUI, and then do various things with JButtons and such. I have the program written but I can't figure out how to accept user input in GUI, and be able to use that input in my methods? I guess I'm looking for a scanner class that can be used in GUI?

我的程序需要输入金额并将其转换为硬币。我需要它有一个 GUI,并且必须能够在 GUI 中输入数量,然后用 JButtons 等做各种事情。我已经编写了程序,但我不知道如何在 GUI 中接受用户输入,以及如何在我的方法中使用该输入?我想我正在寻找可以在 GUI 中使用的扫描仪类?

回答by user3437460

You need to have JTextField placed in your gui. Input should be done on the textboxes. You also need Jbutton. Buttons are needed for interaction between the user and your program. You can have button like "calculate".

您需要将 JTextField 放置在您的 gui 中。输入应该在文本框上完成。您还需要 Jbutton。用户和程序之间的交互需要按钮。你可以有像“计算”这样的按钮。

So how does the program knows what to do with the buttons? You also need actionListener for the buttons. So you code your logic/actions to be performed in your actionListener.

那么程序如何知道如何处理按钮呢?您还需要按钮的 actionListener。因此,您编写了要在 actionListener 中执行的逻辑/操作。

The actionListener listens for actions (E.g.button press) so that respective actions can be performed.

actionListener 侦听动作(Egbutton 按下),以便可以执行相应的动作。

How user interacts with the program with a GUI is very different from a console program. You no longer use scanner to scan for user input.

用户通过 GUI 与程序交互的方式与控制台程序有很大不同。您不再使用扫描仪来扫描用户输入。

In consoleprogram you do this:

控制台程序中,您可以这样做:

Scanner scn = new Scanner(System.in);
String input = scn.nextLine();

In GUIyou do this instead:

GUI 中,您可以这样做:

JTextField txtInput = new JTextField("");

public class txtInputListener implements ActionListener
{
    public void actionPerformed(ActionEvent event)
    {
        input = txtInput.getText();   //receive input from text field
        System.out.println(input);
    }
}

This is not the full code, but it gives you the idea.

这不是完整的代码,但它为您提供了思路。