3

I want to be able to type into a textbox and as the user types into the textbox i want the program to automatically read the textbox without the need of clicking a button.

Example: User types: "abcd" and as the user typed it, the program displayed the corresponding number to each letter.

Program outputs: "1234"

As in: a -> 1; b -> 2; etc.

Im using "private void mycode()" to write my code. I saw that if I made it static I could use java.util.concurrent.TimeUnit (https://stackoverflow.com/a/24104427/12577450) but then mycode() would not work right with my variables.

Can someone please help me?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Max SF
  • 43
  • 6

1 Answers1

1

You can use the DocumentListener class.

Take a look at https://docs.oracle.com/javase/7/docs/api/javax/swing/event/DocumentListener.html

import javax.swing.*;
import javax.swing.event.*;
import java.io.Serializable;

public class MyFrame extends JFrame implements Serializable {
    private static final long serialVersionUID = 123;
    private JTextField field1, field2;

    public MyFrame() {
        super.setSize(600, 400);
        super.setPreferredSize(new java.awt.Dimension(600, 400));
        super.setResizable(false);
        field1 = new JTextField();
        field2 = new JTextField();
        super.add(field1);
        super.add(field2);
        field1.setLocation(0, 0);
        field1.setSize(600, 200);
        field2.setLocation(0, 200);
        field2.setSize(600, 200);
        field2.setEditable(false);
        super.setLocationRelativeTo(null);
        field1.getDocument().addDocumentListener(new DocumentListener() {
            public void changedUpdate(DocumentEvent e) {
              f();
            }
            public void removeUpdate(DocumentEvent e) {
              f();
            }
            public void insertUpdate(DocumentEvent e) {
              f();
            }
            public void f(){
                String new_str = "";
                for (char c : field1.getText().toCharArray()) {
                    if (c >= 'a' && c <= 'z')
                        new_str += (int) (c - 'a' + 1); // is this what you want?
                    else
                        new_str += c;
                }
                field2.setText(new_str);
                field2.setBounds(0, 200, 600, 200);
            }
        });
        super.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        super.setVisible(true);
    }

    public static void main(String[] args) {
        new MyFrame();
    }
}
Dinu
  • 129
  • 2
  • 6
  • Thank you for your quick reply! What i want is to use the value being typed into the textbox instantly as it is being typed. I tried using a "for loop" but the program tends to crash. – Max SF Dec 24 '19 at 23:52
  • You can use the `insertUpdate` method for that – Dinu Dec 24 '19 at 23:55