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

前端 未结 3 914
死守一世寂寞
死守一世寂寞 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.

提交回复
热议问题