如何将数据从 DATA class 中的方法发送到 guiTest class 中的 jTextArea

How do I send data from a method in DATA class to a jTextArea in guiTest class

如何将数据从 Data class 中的方法发送到 GUITest class 中的 JTextAreaSystem.out.println 重定向JTextArea?

我需要以仅当 DataOut 方法中的数据更新时才发送的方式执行此操作,而不是从主方法轮询新数据。

这是示例代码

    public class GUITest 

    private JFrame frame;
    JTextArea textArea_1 = new JTextArea();
    
    public static void main(String[] args) throws InterruptedException, IOException {
        
        System.out.println ("Thread Name 0 "+ Thread.currentThread().getName());
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    GUITest window = new GUITest();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        
        Data data = new Data();
        
        for(int i = 0; i < 100; i++) {
            Thread.sleep(20);
            data.DataOut();
        }
    }

    public GUITest() throws IOException {
    
        initialize();
    }
        
    public  void initialize() throws IOException {
        frame = new JFrame();
        frame.setBounds(1200, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        
        textArea_1.setBounds(120, 45, 100, 23);
        textArea_1.setText("");
        frame.getContentPane().add(textArea_1);
    }
}
    import java.io.IOException;

    public class Data {

    public void DataOut() throws IOException {
        int S = 0;
        for(int i = 0; i < 20; i++) {
            S++;
        }
        System.out.println(S);  // This should print to the JTextArea of class GUITest
    }
}

有多种方法可以做到这一点。我首先想到的是:

让Dataclass构造函数接受GUITest的一个实例,所以它变成:

Data data = new Data(this);

数据变为:

public class Data{
  GUITest istance;

  public Data(GUITest istance){
     this.istance=istance;
  }
}

然后,在 GUITest 中创建一个名为 setTextAreaMessage(String message) 的方法,并在数据 class 中创建一个方法,而不是 System.out.println(S); 你调用 istance.setTextAreaMessage(S); 不要忘记使用 text_Area1.setText(message);

行在 setTextAreaMessage(String message) 方法中设置文本

此解决方案有效,但老实说,我不记得是否可以将像 jTextArea 这样的小部件声明为静态的。如果可以的话,你可以做类似GUITest.text_Area1.setText(S);

的事情