您的问题不是 Swing 或 GUI 特定的,而是更一般的 Java 问题的一部分:
一个类的对象如何改变另一个类的对象的字段状态?
一种方法是使用 setter 方法。例如,您可以为持有 JTextArea 的类提供一个公共方法,该方法将使其他类能够执行此操作。
例如,
// assuming the class holds a descriptionArea
// JTextArea field
public void appendToDescriptionArea(String text) {
descriptionArea.append(text);
}
这样,JTextArea 字段可以保持私有,但其他类拥有对显示的包含该字段的 GUI 的有效引用可以调用此方法并更新 JTextArea 的文本。请注意,一个常见的错误是为希望添加文本的类提供对包含 JTextArea 的类的全新且完全唯一的引用,但如果这样做,您将设置不显示的 GUI 的文本。因此,请确保在正确的可视化实例上调用此方法。
如果此答案不能帮助您解决问题,请考虑发布有关所涉及类的更多信息,包括相关代码和背景信息。您可以向我们提供的信息越具体和有用,通常我们可以为您提供的答案就越具体和有帮助。
编辑
关于这个错误:
"textArea 无法解析"
还有这段代码:
public FrameGUI(String title) {
super(title);
setLayout(new BorderLayout());
final JTextArea textArea = new JTextArea(); // *****
detailsPanel = new DetailsPanel();
Container c = getContentPane();
c.add(textArea, BorderLayout.CENTER);
c.add(detailsPanel, BorderLayout.NORTH);
}
你的问题是你在 FrameGUI 的构造函数中声明你的 textArea 变量,并且在这样做时,变量的可见性或“范围”仅限于这个构造函数。在构造函数之外它不存在并且不能使用。
解决方法是在构造函数outside声明textArea变量,使其成为类的字段。例如:
public class FrameGUI extends JFrame { // I'm not a fan of extending JFrames.
// this variable is now visible throughout the class
private JTextArea textArea = new JTextArea(15, 40); // 15 rows, 40 columns
public FrameGUI(String title) {
super(title);
setLayout(new BorderLayout());
// final JTextArea textArea = new JTextArea(); // *** commented out
detailsPanel = new DetailsPanel();
Container c = getContentPane();
c.add(new JScrollPane(textArea), BorderLayout.CENTER); // put textarea into a scrollpane
c.add(detailsPanel, BorderLayout.NORTH);
}
public void appendToTextArea(String text) {
textArea.append(text);
}