0

I am working on a Swing form. When the user changes text in a TextField, I want to get input from other fields, do some calculations and then display the results. How can I do that?

Here is what I have so far:

jTextField3.addKeyListener(

    new KeyAdapter() {
        public void keyTyped(KeyEvent e){
           char c = e.getKeyChar();
           if('0'<=c && c<='9') {
                String a = jTextField6.getText().toString();
                String l = jTextField7.getText().toString();
                int m = Integer.parseInt(a);
                int n = Integer.parseInt(l);
                jTextField13.setText("" + m*n);
          }
       }
    });
Stan Kurdziel
  • 5,476
  • 1
  • 43
  • 42
Hamza Shahid
  • 19
  • 1
  • 6
  • Please make the tone less obnoxious... It's discouraging people from answering it. Edit the question and clarify exactly what problem you are having. – deezy Jul 10 '15 at 23:42
  • 1
    Also mention what error you are getting and attach the error logs if possible – user3653796 Jul 10 '15 at 23:43
  • Use a DocumentFilter to control what can be entered into a field and a DocumentListener to monitor changes. Have a look at [Implementing a Document Filter](http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter), [DocumentFilter Examples](http://www.jroller.com/dpmihai/entry/documentfilter) and [Listening for Changes on a Document](http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#doclisteners) for more detalls – MadProgrammer Jul 10 '15 at 23:54
  • 2
    This question is too vague. What happens when you run the code you have attached? – Stan Kurdziel Jul 11 '15 at 00:36
  • 1
    Please explain in which you got stuck. Don't expect us to get complete code with example. Just mention - what you did, what you want and what you are getting. It will be easy to solve your problem. – Puneet Chawla Jul 11 '15 at 04:55
  • actually i am using document listener to monitor changes to two textfields. but now when there is no value in textfield and user press backspace button then it shows error "for input empty string" this where m stuck now. – Hamza Shahid Jul 12 '15 at 22:39

1 Answers1

4

If you want to monitor for changes to one or more text fields, you should be using a DocumentListener, this will also provide you notification's of when the user pastes text into the field or the field is changed programatically (via a call to setText)

For example...

Bunnies

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class Text {

    public static void main(String[] args) {
        new Text();
    }

    public Text() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());

            JTextField field1 = new JTextField(10);
            JTextField field2 = new JTextField(10);
            JTextField field3 = new JTextField(10);

            DocumentListener dl = new DocumentListener() {

                @Override
                public void insertUpdate(DocumentEvent e) {
                    updateFieldState();
                }

                @Override
                public void removeUpdate(DocumentEvent e) {
                    updateFieldState();
                }

                @Override
                public void changedUpdate(DocumentEvent e) {
                    updateFieldState();
                }

                protected void updateFieldState() {
                    String text = field1.getText() + " " + field2.getText();
                    field3.setText(text);
                }
            };

            field1.getDocument().addDocumentListener(dl);
            field2.getDocument().addDocumentListener(dl);
            field3.setEditable(false);

            add(field1);
            add(field2);
            add(field3);
        }

    }

}

Now, it appear that you are trying to limit the character that can be typed into the field. You could use a JSpinner or JFormattedTextField, but these only provide post validation.

For real time validation, you should be using a DocumentFilter, which will allow you to intercept what is entered into the field before it's applied to the underlying Document.

See Implementing a DocumentFilter and DocumentFilter examples for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • May I know what software are you using to create the animated gif? – user3437460 Jul 11 '15 at 05:40
  • 2
    It's a trade secret ;) [licecap](http://www.cockos.com/licecap/), it's free and cross platform – MadProgrammer Jul 11 '15 at 05:55
  • I want to +1 to thank you for sharing with me the software and of course for the nice answer ;) – user3437460 Jul 11 '15 at 20:39
  • Document listener works but when there is one digit in textfield and user press backspace button it throws an error for empty input string. now i am stucked there ? what should i do now? – Hamza Shahid Jul 12 '15 at 22:34
  • I assume you mean you're doing `Integer.parseString` on an empty `String`? Maybe test the `String` value first using `String#isEmpty` and defaulting the value to `0` when it is...or some such – MadProgrammer Jul 12 '15 at 22:37