首页 > 解决方案 > 如何将数据从 DATA 类中的方法发送到 guiTest 类中的 jTextArea

问题描述

如何将数据从类中的方法发送DataJTextArea类中GUITest,或System.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
    }
}

标签: javaswingjtextarea

解决方案


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

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

Data data = new Data(this);

和数据变成:

public class Data{
  GUITest istance;

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

然后,在 GUITest 调用setTextAreaMessage(String message)和 Data 类中创建一个方法,而不是System.out.println(S);你调用istance.setTextAreaMessage(S); 不要忘记在setTextAreaMessage(String message)方法内设置文本与行text_Area1.setText(message);

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


推荐阅读