Search code examples
javaswingnetbeansjtextfield

how to change Jtextbox values without using Jbutton using netbeans


I want to create a small Netbeans application related to school students. I have two JTextFields. In this JTextFields I want to show some words like "apple", then want to show "mango" etc.

The details are as follows.

  1. When the application is start I want to show in JtextField1 as "apple". When the student type it as same or wrong entry then auto move to next word "mango" in same JTextfield1.

  2. In this application JButton will not be use.


Solution

  • I'm guessing that you have two JTextFields, one that the user is not supposed to edit and is for display only -- so make that field non-editable by

    1. calling setFocusable(false) so the JTextField can never receive focus
    2. And if you desire, calling setEditable(false)

    In your 2nd JTextField, give it an ActionListener via addActionListener(...) that inside of the listener have the code check the 2nd JTextField's text and if incorrect, change the text in the first JTextField.

    firstTextField.setFocusable(false);
    firstTextField.setEditable(false);
    
    secondTextField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String text = secondTextField.getText();
    
            // here check the text String and if incorrect
            // call setText(...) on the firstTextField
        }
    });
    

    Note that by adding an ActionListener to the JTextField itself, you now have a listener that is activated when the user presses the enter button when this field has focus. No need for a JButton for this to work.