user1765804 user1765804 - 4 months ago 24
Java Question

JAVA: Save user input as a string in a Jframe GUI

Noob here. I have been browsing for hours, and I still cannot figure out the proper way to get user input to be saved as a string from a text field in my Jframe. Any help would be appreciated. I want to save the user's text into the variable userWords.

package cipher;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;

public class cipherApp extends JFrame {


private static final int WIDTH = 700;
private static final int HEIGHT = 700;

private String userWords; // stores user input into a string

public cipherApp(){
setTitle("Camo Cipher");
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

}
public static void main(String[] args){
cipherApp newInstance = new cipherApp();

}
}

Answer

You have to use a JTextField and a JButton to submit the use input:

public class Test extends JFrame {

    String userWord = "";
    JTextField userInput = new JTextField(10);
    JButton submit = new JButton("Submit");

    public Test() {
        super("Camo Cipher");
        JPanel centerPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // This center the window on the screen
        submit.addActionListener( (e)-> {
            submitAction();
        });
        centerPanel.add(userInput);
        JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
        southPanel.add(submit);
        Box theBox = Box.createVerticalBox();
        theBox.add(Box.createVerticalStrut(100));
        theBox.add(centerPanel);
        theBox.add(Box.createVerticalStrut(200));
        theBox.add(southPanel);
        add(theBox);
    }

    private void submitAction() {
        // You can do some validation here before assign the text to the variable 
        userWord = userInput.getText();
    }

    public static void main(String[] args) {
        new Test().setVisible(true);
    }
}
Comments