Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something at variable change in Java

I want to do the following: As soon as a specific Variable (roomName) changes its Value, the Title of a JFrame should be changed to the new Value of roomName. My only problem is, that the JFrame is already built before the roomName changes.

This is a little snippet of my Connection.java Class:

public Connection() {
    ...
    fieldName.addKeyListener(new KeyListener() {
        public void keyPressed(KeyEvent e) {
            if(e.getKeyChar() == KeyEvent.VK_ENTER) {
                setName();
            }
        }
    });
}

public void setName(){
    ChatFrame.frame.setVisible(true);
    ChatFrame.roomName = fieldName.getText();
    this.dispose();
}

The other Class ChatFrame.java should do the described Action above. Do I need a Listener or a Thread for this? What's the best way to do it?

like image 325
muffin Avatar asked Jul 08 '26 17:07

muffin


1 Answers

One simple solution that springs to mind is to wrap the variable up into an object, then the setter method can look like this:

public void setNewValue(String newVal)
{
    if(!newVal.equals(currentVal)) {
        currentVal = newVal;
        // Value has changed. Call the relevant code.
    }
}
like image 87
christopher Avatar answered Jul 11 '26 15:07

christopher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!