简体   繁体   English

从另一个类在 JTextArea 中写一行

[英]Writing a line in a JTextArea from another class

I'm trying to use a Method in my class 'Visual' to write a line of code into a JTextArea and it prints when I call it from 'Visual' but when I call it from 'Login' It only prints Text into the Console, not to the TextArea.我正在尝试使用我的类“Visual”中的方法将一行代码写入 JTextArea,当我从“Visual”调用它时它会打印,但是当我从“登录”调用它时它只将文本打印到控制台,而不是TextArea。

private static Visual Visual;
Visual.WriteLine("I'm sorry, your username or password is incorrect. Please try again.");

or或者

private static Visual Visual = new Visual();
Visual.WriteLine("I'm sorry, your username or password is incorrect. Please try again.");

Dont work form 'Login'不要使用“登录”表单

But,但,

WriteLine("Test"); 

works from 'Visual', the class that the method is in.从“Visual”工作,该方法所在的类。

Here's the method in 'Visual'这是'Visual'中的方法

public void WriteLine(String Text) {
    System.out.println(Text);
    SystemFeed.append(Text.toString() + "\n");
    SystemFeed.setCaretPosition(SystemFeed.getDocument().getLength());
}

I can only guess based on the information so far presented (meaning please give us more pertinent information about your problem!) but I fear that you may be having a reference problem, that the GUI reference that you're trying to write to is not the same as the one displayed.我只能根据目前提供的信息进行猜测(意思是请给我们提供有关您的问题的更多相关信息!)但我担心您可能遇到参考问题,您尝试写入的 GUI 参考不是和显示的一样。 Suggestions:建议:

  • Get rid of all unnecessary static variables, including the Visual variable.去掉所有不必要的静态变量,包括 Visual 变量。 Make them instance variables.使它们成为实例变量。
  • If you get an errors by doing this, the solution is not to make Visual static but to get a reference to a proper instance of this class.如果执行此操作时出现错误,解决方案不是使 Visual 成为静态,而是获取对此类的正确实例的引用。
  • Check how many times your program calls new Visual(...) in it.检查您的程序在其中调用new Visual(...)的次数。 It should only make this call once.它应该只进行一次这个调用。 Consider putting a System.out.println("New Visual created") in the Visual constructor to see that this is so.考虑在 Visual 构造函数中放置一个System.out.println("New Visual created")以查看是否如此。
  • Pass a valid reference to the visualized GUI to any objects that need to call methods on this object.将可视化 GUI 的有效引用传递给需要调用此对象上的方法的任何对象。 So if your Login object needs to call a method of the Visual object, give Login a public void setVisual(Visual visual) method that would allow it to accept the correct Visual reference, make sure that this method is called once during set up of the Login class, and then make sure that in Login you make your Visual method calls with this reference.因此,如果您的 Login 对象需要调用 Visual 对象的方法,请为 Login 提供一个public void setVisual(Visual visual)方法,以允许它接受正确的 Visual 引用,确保在设置期间调用此方法一次Login 类,然后确保在 Login 中使用此引用进行 Visual 方法调用。

Again if this doesn't help, then tell and show us more, preferably an sscce .同样,如果这没有帮助,那么告诉我们更多,最好是sscce

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

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