JAVA Swing - Setting JLabel equal to a String in a

2020-02-15 08:12发布

问题:

I have a method called getTheUserInput in a class which returns a String which updates based on user actions, which is located inside a class called Board.java. I have action which adds data to a String which I know works.

In my other class I have a JLabel which has been set to equal the returned String of the method, as follows:

JLabel l = new JLabel(b.getTheUserInput());

However, when I run the application no matter what input the user provides, the string updates, but the JLabel stays blank. How do I keep the JLabel updated consistently with the string in the other class?

回答1:

You'd .... need to update the JLabel.

myJLabel.setText(newString);

Strings in Java are immutable so they can never change / be changed.

For example when you say, "I have action which adds data to a String which I know works." ... you're incorrect. You've created a new String. You need to supply the JLabel with the new String (the user's input) if you want to change the text.

Edit: To answer the last part of your question; you'd need to keep track of the JLabel and update it as I show above every time the user provides input (in the event handler for whatever that is). Using the Observer Pattern might be an option as Java provides it via Observer and Observable



回答2:

That label is set by default with whatever gets returned by b.getTheUserInput() initially. If the output of b.getTheUserInput() changes, the label doesn't find out and so doesn't change its text.

The easiest way to fix this is to call l.setText(b.getTheUserInput()) whenever b.getTheUserInput() has new output.

Another way is to write a listener (such as a ChangeListener) that sends out an event whenever b.getTheUserInput() has new output, then have the label add the listener and change its text when an event is received. This may seem more complicated initially, but the advantage is that Board does not need to know about the label or anything else that might want to access its output in future.



回答3:

There are two possibilities.

First is to update the text l.setText(b.getTheUserInput()); other option is that you did not add the label to a container.