简体   繁体   English

在不同的类中使用 JTextArea

[英]Using a JTextArea in a different class

I have a class for my GUI which I created using Swing UI Designer.我有一个使用 Swing UI Designer 创建的 GUI 类。 All the components were automatically made private but now I need output some text in a variable called consoleTextArea from outside of the UI.class When I set consoleTextArea to public static I get an error saying "UI.form: Cannot bind: field is static: indeed.UI.consoleTextArea"所有组件都自动设为私有,但现在我需要从 UI.class 外部在名为 consoleTextArea 的变量中输出一些文本当我将 consoleTextArea 设置为 public static 时,我收到一条错误消息“UI.form:无法绑定:字段是静态的:确实.UI.consoleTextArea”

...
public static JTextArea consoleTextArea;
...
...
UI.consoleTextArea.setText("abc");
...

\\src\\indeed\\UI.form: Cannot bind: field is static: indeed.UI.consoleTextArea \\src\\indeed\\UI.form:无法绑定:字段是静态的:indeed.UI.consoleTextArea

You can change the value of your label/textArea, through an instance of your UI class.您可以通过 UI 类的实例更改标签/文本区域的值。

public class UI {

  // ...

  private TextArea consoleTextArea = new TextArea();
  //
  public void setTextInTextArea(String text) {
    this.consoleTextArea.setText(text);
  }
}

Having setters like this, you can manipulate your textArea from within a different class.拥有这样的 setter,您可以从不同的类中操作您的 textArea。 This other class, however, must have access to the instance of UI, either instantiate it itself, or getting it passed as a parameter然而,另一个类必须有权访问 UI 的实例,或者实例化它本身,或者将它作为参数传递

public class OtherClass {
  UI ui = new UI();

  public void doSomething() {
    ui.setTextInTextArea("New text");
  }

}

or something like:或类似的东西:

public class OtherClass {
  public void doSomething(UI ui) {
    ui.setTextInTextArea("New Text");
  }
}

Instead of making the field public (not static public ) you should rather add a method like this to your class:您应该将这样的方法添加到您的类中,而不是将字段设为public (而不是static public ):

public void setConsoleTextArea(String value) { consoleTextArea.setText(value); }

Then you can do然后你可以做

UI.setConsoleTextArea("abc");

without having to mess with the consoleTextArea field that is automatically generated.不必弄乱自动生成的consoleTextArea字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM