从 Java 中的不同 class 追加到私有 TextArea
Appending to a private TextArea from a different class in Java
class Backend extends UI {
// some code
void start() {
txtRespond.append(Bot + ": hello, " + Name + "\n"); /* have a problem accessing txtRespond */
public class UI extends javax.swing.JFrame {
// some code
private javax.swing.JTextArea txtRespond;
我正在尝试从另一个 class 向我的 JTextArea
添加句子。
您无法访问父级的 private
变量,使变量 txtRespond
protected
或为该变量创建 getter。
正如我最初在您发布问题时在评论中提到的那样,您需要将私有字段标记为受保护,以便子 class 可以访问它或提供突变方法。
第二种方法更好,因为它保护了封装。
public class UI extends javax.swing.JFrame {
// some code
private javax.swing.JTextArea txtRespond;
protected void appendResponse(String response){
txtRespond.append(response);
}
// your other methods and code if you have.
}
class Backend extends UI {
// some code
void start() {
appendResponse(Bot + ": hello, " + Name + "\n");
}
}
让 class 负责修改其状态是一种很好的做法。我们应该避免让它们成为非私有的。
*P.S。如果 bot, Name 在 parent class 中定义,那么你可以只传递字符串的变体部分并将其作为参数传递给父方法(当然你需要修改方法的签名以接受多个字符串)在方法定义中,您可以根据要求处理字符串的合并。
class Backend extends UI {
// some code
void start() {
txtRespond.append(Bot + ": hello, " + Name + "\n"); /* have a problem accessing txtRespond */
public class UI extends javax.swing.JFrame {
// some code
private javax.swing.JTextArea txtRespond;
我正在尝试从另一个 class 向我的 JTextArea
添加句子。
您无法访问父级的 private
变量,使变量 txtRespond
protected
或为该变量创建 getter。
正如我最初在您发布问题时在评论中提到的那样,您需要将私有字段标记为受保护,以便子 class 可以访问它或提供突变方法。
第二种方法更好,因为它保护了封装。
public class UI extends javax.swing.JFrame {
// some code
private javax.swing.JTextArea txtRespond;
protected void appendResponse(String response){
txtRespond.append(response);
}
// your other methods and code if you have.
}
class Backend extends UI {
// some code
void start() {
appendResponse(Bot + ": hello, " + Name + "\n");
}
}
让 class 负责修改其状态是一种很好的做法。我们应该避免让它们成为非私有的。
*P.S。如果 bot, Name 在 parent class 中定义,那么你可以只传递字符串的变体部分并将其作为参数传递给父方法(当然你需要修改方法的签名以接受多个字符串)在方法定义中,您可以根据要求处理字符串的合并。