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

问题描述

如何将数据从Data类的方法发送到JTextArea类的GUITest重定向System.out.println的{​​{1}}? >

我需要以这样一种方式进行操作:仅当更新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,23);
        textArea_1.setText("");
        frame.getContentPane().add(textArea_1);
    }
}

解决方法

有多种方法可以做到这一点。我想到的第一件事是:

让Data类构造函数接受一个GUITest的距离,因此它变为:

Data data = new Data(this);

数据变为:

public class Data{
  GUITest istance;

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

然后,在GUITest和Data类中创建一个名为setTextAreaMessage(String message)的方法,而不是System.out.println(S);来调用istance.setTextAreaMessage(S); 不要忘了在setTextAreaMessage(String message)方法中用行text_Area1.setText(message);

设置文本

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

的操作