Editing JLabel text from another class

So what I'm trying to do is edit the text of my JLabel from another class. I do this with label.setText ("bla bla"); but that doesn't affect my JLabel.

My code in a GUI class looks something like this:

public class GUI {

    JFrame f1 = new JFrame("GUI");
    JLabel l1 = new JLabel("Output");
    JTextField tf1 = new JTextField("");

    public run(){  // main calls this method.

    Listener listener = new Listener();

    f1.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    f1.setBounds(450, 170, 400, 400);
    f1.setVisible(true);
    f1.setResizable(false);
    f1.setLayout(null);

    l1.setBounds(8, 8, 200, 30);
    listener.listen(tf1);

    f1.add(l1);
    }
}

      

and then I have this listener class that needs to make changes to the JLabel based on user input. Here is the code:

public class Listener {

    GUI gui = new GUI();

    public void listen(final JTextField textfield) {

        textfield.getDocument().addDocumentListener(new DocumentListener() {

            public void changedUpdate(DocumentEvent e) {
                test();
            }

            public void removeUpdate(DocumentEvent e) {
                test();
            }

            public void insertUpdate(DocumentEvent e) {
                test();
            }

            public void test() {
                if (gui.everythingOK()) { // everythingOK is just a boolean that test if input is valid number and returns true if it is.
                    gui.l1.setText("No errors."); // this code is supposed to change JLabels text.
                } else {
                    gui.l1.setText("Error."); // this code is supposed to change JLabels text.
                }
            }
        });
    }
}

      

The allOK method works great, you just need to trust me with this. It works if I define the JLabel to be static, but it only works the first time. After the first change, there are no more changes appearing in the JLabel, so defining the statics doesn't help me. I hope there is someone who knows what is wrong with this code. And don't mind if there are obvious mistakes, because I only took the most important parts of a very long code.

Thanks in advance.

Here is my allOK code:

public boolean everythingOK() {
        if (hasInt(tf1) && isValid(tf1)) {
            return true;
        } else {
            return false;
        }
    }

    public boolean hasInt(JTextField textfield) {
        try {
            Integer.parseInt(textfield.getText());
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public boolean isValid(JTextField textfield) {
        if (hasInt(textfield)) {
            if (Integer.parseInt(textfield.getText()) >= minValue && Integer.parseInt(textfield.getText()) <= maxValue) {
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }

    }

      

+3


source to share


1 answer


Your Listener class creates another Gui instance.

GUI gui = new GUI();

      

The code in Listener.test () changes the l1 label in this Gui instance, not the displayed Gui.

You must give the listener a reference to the real Gui object.

You may also need to wrap the code that sets the new shortcut in SwingUtilities.invokeLater so that it runs from the event dispatch thread.



SwingUtilities.invokeLater(new Runnable() {
    public void run() {
      <guiInstance>.l1.setText("Query: " + queryNo);
    }
  });

      

UPDATE: Here is some sample code that does what you want. You can take it as it is and play with it. See how the GUI class provides its own Listener instance when it creates it (new Listener (this). If the textbox contains text, the label prints "No errors", otherwise the prints are "Error".

In this case, the SwingUtilities.invokeLater part is unnecessary. But if you keep developing your program and start adding background threads that want to update the interface, then you need to do it this way. Just a warning for later ...; -)

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;

public class GUI {

    JFrame f1 = new JFrame("GUI");
    JLabel l1 = new JLabel("Output");
    JTextField tf1 = new JTextField("");

    public void run(){  // main calls this method.
        f1.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        f1.setBounds(450, 170, 400, 400);
        f1.setVisible(true);
        f1.setResizable(false);
        f1.setLayout(new GridLayout(2,1));

        f1.add(l1);
        f1.add(tf1);

        f1.pack();

        Listener listener = new Listener(this);
        listener.listen(tf1);
    }

    public static void main(String[] args) {
        new GUI().run();
    }

    public boolean everythingOK() {
        return tf1.getText().length() > 0;
    }

    class Listener {
        private GUI gui;

        public Listener(GUI gui) {
            this.gui = gui;
        }

        public void listen(final JTextField textfield) {

            textfield.getDocument().addDocumentListener(new DocumentListener() {

                public void changedUpdate(DocumentEvent e) { test(); }
                public void removeUpdate(DocumentEvent e) { test(); }
                public void insertUpdate(DocumentEvent e) { test(); }

                public void test() {
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            if (gui.everythingOK()) { // everythingOK is just a boolean that test if input is valid number and returns true if it is.
                                gui.l1.setText("No errors."); // this code is supposed to change JLabels text.
                            } else {
                                gui.l1.setText("Error."); // this code is supposed to change JLabels text.
                            }
                        }
                    });
                }
            });
        }
    }
}

      

+3


source







All Articles