swift
swift

Reputation: 75

Proper way to get user input via GUI

If I use a GUI text field do I still need to use scanner?

I have this in my GUI class to get the users input

JButton startButton = new JButton("Start");
    startButton.setBounds(75, 94, 210, 32);
    getContentPane().add(startButton);

    targetInput = new JTextField();
    targetInput.setBounds(75, 50, 210, 33);
    targetInput.setHorizontalAlignment(SwingConstants.CENTER);
    targetInput.setToolTipText("");
    getContentPane().add(targetInput);
    targetInput.setColumns(1);

How would I call that in my Main class?

If I was calling from the console I would simply just import scanner and call for an input. However since it is in GUI I am not sure how to proceed.

Upvotes: 0

Views: 33

Answers (2)

shan1024
shan1024

Reputation: 1399

You can simply get the text from a JTextField using getText() method.

Ex: String inputString = targetInput.getText();

If you want to get the text when the button is clicked, add an ActionListener to the button.

Ex:

startButton.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        String inputString = targetInput.getText();//get the text
        System.out.println(inputString);//print it
    }
});

Upvotes: 1

Austin
Austin

Reputation: 4929

You just need to do

String input = targetInput.getText();

Upvotes: 1

Related Questions