如何解决如何将数据从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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。