java - 如何将数据从 DATA 类中的方法发送到 guiTest 类中的 jTextArea
问题描述
如何将数据从类中的方法发送Data
到JTextArea
类中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
}
}
解决方案
有多种方法可以做到这一点。我首先想到的是:
让 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);
推荐阅读
- google-apps-script - 仅将值从一个谷歌表复制到另一个的脚本不起作用
- python - 与我的 MYSQL connect_timeout 单位混淆
- python - 在给定条件下更新矩阵中的条目
- git - 您可以仅使用 IDX 和 PACK 文件重建 repo 吗?
- c++ - 一元和二元运算符之间的性能差异
- go - go数组存储为字符串-如何转换为数组
- google-app-engine - 如何为 nodejs Google App Engine 项目制作基本的 app.yaml 文件
- cross-browser - 为什么我的字体大小在 Firefox 和 chrome 移动浏览器上显示不同?
- kubelet - Microk8s 将 kubelet.service 保存在哪里?
- typescript - 基于可写性的 Typescript 条件类型