JAVA Swing - 将JLabel设置为等于另一个类中的String [英] JAVA Swing - Setting JLabel equal to a String in another class

查看:419
本文介绍了JAVA Swing - 将JLabel设置为等于另一个类中的String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在类中有一个名为 getTheUserInput 的方法,该类返回一个基于用户操作更新的String,该操作位于名为Board.java的类中。我有动作将数据添加到我知道有效的字符串。

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.

在我的另一个类中,我有一个JLabel,它被设置为等于方法的返回String,如下:

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());

然而,当我运行应用程序时,无论用户提供什么输入,字符串都会更新,但是JLabel保持空白。如何使JLabel与其他类中的字符串保持一致?

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?

推荐答案

你需要...更新 JLabel

myJLabel.setText(newString);

Java中的字符串 s是不可变的,所以他们永远不会改变/改变。

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

例如,当你说我有动作将数据添加到我知道可行的字符串时。 ......你错了。您已经创建了一个新的 String 。如果要更改文本,则需要使用新的 String (用户的输入)提供 JLabel

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.

编辑:回答问题的最后部分;你需要跟踪 JLabel 并按照我在每次用户提供输入时显示的内容进行更新(在事件处理程序中用于任何内容)。使用观察者模式可能是一个选项,因为Java通过 Observer <提供它/ code>和 Observable

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

这篇关于JAVA Swing - 将JLabel设置为等于另一个类中的String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆