JAVA Swing - Setting JLabel equal to a String in another class

前端 未结 3 901
死守一世寂寞
死守一世寂寞 2020-12-21 21:02

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.

相关标签:
3条回答
  • 2020-12-21 21:06

    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.

    0 讨论(0)
  • 2020-12-21 21:11

    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.

    0 讨论(0)
  • 2020-12-21 21:25

    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

    0 讨论(0)
提交回复
热议问题