如何在 GUI 中接受用户输入?- 爪哇 [英] How to accept user input in GUI? - Java

查看:48
本文介绍了如何在 GUI 中接受用户输入?- 爪哇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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".

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

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 监听动作(例如按下按钮),以便可以执行相应的动作.

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

用户通过 GUI 与程序交互的方式与控制台程序非常不同.您不再使用扫描仪来扫描用户输入.

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.

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

In console program you do this:

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

GUI 中,您可以这样做:

In GUI you do this instead:

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.

这篇关于如何在 GUI 中接受用户输入?- 爪哇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆