Saving variables in swing Text field

Solution 1:

Try this code, read the comments to understand the code. I hope this code helps you.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

class main {

    static String var; // The text input gets stored in this variable

    public static void main(String args[]) {
    
        JFrame frame = new JFrame("Chat Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);


        JPanel panel = new JPanel();
        JLabel label = new JLabel("Enter Base:");
        JTextField tf = new JTextField(2);
        panel.add(label);
        panel.add(tf);
           
    
        frame.getContentPane().add(BorderLayout.SOUTH, panel);
        frame.setVisible(true);
    
        tf.addActionListener(new ActionListener() { // Action to be performed when "Enter" key is pressed
            @Override
            public void actionPerformed(ActionEvent e) {
                var = tf.getText(); // Getting text input from JTextField(tf)
            }
        });
    }
}