gpt4 book ai didi

java - 从 Java 中的不同类追加到私有(private) TextArea

转载 作者:行者123 更新时间:2023-12-02 12:56:22 26 4
gpt4 key购买 nike

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;

我正在尝试从不同的类向我的 JTextArea 添加句子。

最佳答案

正如我在您发布问题时最初在评论中提到的那样,您需要将私有(private)字段标记为 protected ,以便子类可以访问它或提供突变方法。

第二种方法更好,因为它可以保护封装。

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");
}
}

让一个类负责修改其状态是一个很好的做法。我们应该避免将它们设为非私有(private)的。

*附注如果 bot、Name 是在父类中定义的,那么您只需传递字符串的变体部分并将其作为参数传递给父方法(当然您需要修改方法的签名以接受多个字符串)并在方法中定义您可以根据要求处理字符串的合并。

关于java - 从 Java 中的不同类追加到私有(private) TextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44416595/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com