在工作线程中读取 GUI 对象数据
Reading GUI Object Data in Worker Threads
我刚刚阅读了 Java 教程中有关 Concurrency in Swing 的课程。它几乎专门处理从工作线程上的方法 运行 返回到调度线程上的方法 运行 的临时和最终结果。我想知道另一个方向的数据流。只要不更改对象的任何数据,工作线程上的方法 运行 是否可以自由读取属于 GUI 对象的变量并调用它们的数据返回方法?
谢谢。
How about reading the entered value from a JTextField or reading the state of a JCheckBox and using those results to influence the method executing on the worker thread?
简单:JTextField 和 JCheckBox 的状态将在 Swing 事件线程上读取,然后信息可能会通过其构造函数(再次在 Swing 事件线程上)传递到 Worker,然后工作从事件线程执行。
OK, I'm thinking about a fairly large amount of data. So, the call to the constructor would be kind of awkward / ugly passing all those parameters.
然后创建一个单独的 class 来保存参数数据,或使用集合,或两者兼而有之。这不是特定于 Swing 或 SwingWorker 的,而是针对将大量数据传递给任何方法或对象的问题的相同解决方案。
Maybe have the constructor itself pull the data from the GUI elements and store in variables for the worker thread?
我投反对票,因为它增加了代码的耦合并降低了内聚性。工作人员应该尽可能不了解 GUI,而应该只专注于获得其数据然后进行工作。出于这个原因,我尝试尽可能多地将 PropertyChangeListeners 与我的工人一起使用。
我刚刚阅读了 Java 教程中有关 Concurrency in Swing 的课程。它几乎专门处理从工作线程上的方法 运行 返回到调度线程上的方法 运行 的临时和最终结果。我想知道另一个方向的数据流。只要不更改对象的任何数据,工作线程上的方法 运行 是否可以自由读取属于 GUI 对象的变量并调用它们的数据返回方法?
谢谢。
How about reading the entered value from a JTextField or reading the state of a JCheckBox and using those results to influence the method executing on the worker thread?
简单:JTextField 和 JCheckBox 的状态将在 Swing 事件线程上读取,然后信息可能会通过其构造函数(再次在 Swing 事件线程上)传递到 Worker,然后工作从事件线程执行。
OK, I'm thinking about a fairly large amount of data. So, the call to the constructor would be kind of awkward / ugly passing all those parameters.
然后创建一个单独的 class 来保存参数数据,或使用集合,或两者兼而有之。这不是特定于 Swing 或 SwingWorker 的,而是针对将大量数据传递给任何方法或对象的问题的相同解决方案。
Maybe have the constructor itself pull the data from the GUI elements and store in variables for the worker thread?
我投反对票,因为它增加了代码的耦合并降低了内聚性。工作人员应该尽可能不了解 GUI,而应该只专注于获得其数据然后进行工作。出于这个原因,我尝试尽可能多地将 PropertyChangeListeners 与我的工人一起使用。