How to accept user input in GUI? - Java [closed]

百般思念 提交于 2021-01-29 18:30:38

问题


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?


回答1:


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

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.

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

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();

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.



来源:https://stackoverflow.com/questions/28017323/how-to-accept-user-input-in-gui-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!