Search code examples
javaswingjtextfieldjtextarea

Update a JTextArea dynamically depending on users JTextField values


I have two JTextField which take numbers from users, like this:

nbMuscle = new JTextField();
nbMuscle.setText("2");

and this:

nbFuyard = new JTextField();
nbFuyard.setText("1");

my JTextArea() takes make an addition of both JTextField's values, like this:

nbPersonnages = new JTextArea();
int nombMusc = Integer.valueOf(nbMuscle.getText());
int nombFuy = Integer.valueOf(nbFuyard.getText());
int nbTotal = nombMusc + nombFuy;
nbPersonnages.setText(String.valueOf(nbTotal));

It works like a charm but I have one problem, if the user edit one of the JTextFields, the JTextArea value don't change. I have found on internet some notions like jTextArea.appened(String str) but it doesn't work.

Any idea of what I could do?


Solution

  • You have to add a DocumentListener to the underlying Document of the TextFields to listen to changes made while the program runs.
    The easiest way to do this is proboably an anonymous class. Here is the Code:

    nbMuscle = new JTextField();
    nbMuscle.setText("2");
    nbFuyard = new JTextField();
    nbFuyard.setText("1");
    
    nbPersonnages = new JTextArea();
    
    DocumentListener dl = new DocumentListener() {
    
        @Override
        public void removeUpdate(DocumentEvent e) {
            textChanged();
        }
    
        @Override
        public void insertUpdate(DocumentEvent e) {
            textChanged();
        }
    
        @Override
        public void changedUpdate(DocumentEvent e) {
            // This method is not called when the text of the Document changed, but if attributes of the Document changed.
        }
    
        private void textChanged() {
            int nombMusc = Integer.valueOf(nbMuscle.getText());
            int nombFuy = Integer.valueOf(nbFuyard.getText());
            int nbTotal = nombMusc + nombFuy;
            nbPersonnages.setText(String.valueOf(nbTotal));
        }
    };
    
    int nombMusc = Integer.valueOf(nbMuscle.getText());
    int nombFuy = Integer.valueOf(nbFuyard.getText());
    int nbTotal = nombMusc + nombFuy;
    nbPersonnages.setText(String.valueOf(nbTotal));
    
    nbMuscle.getDocument().addDocumentListener(dl);
    nbFuyard.getDocument().addDocumentListener(dl);