Swing/SwingWorker 初学者问题
我正在尝试用 java 实现 GUI,但我是 swing 的初学者。我想澄清一件事。我读到,为了保持 GUI 的响应能力,我应该使用 SwingWorker 类在单独的线程中执行任务。到目前为止还好。 不,我有一个包含大约 15 个远程方法的模型。每个方法返回的对象类型都与其他方法不同。 在我看来,用户按下按钮并调用模型中的适当方法。如果不使用 swingworker,GUI 就会冻结。我的问题是,我是否应该创建 Swingworker 线程的 15 个子类,并根据用户的操作根据需要创建每个子类的新实例?我的理解正确吗?有没有标准的方法或者我所说的是正确的方法?
谢谢!
I am trying to implement a GUI in java but I am beginner in swing. I want to make something clear. I read that in order to keep the GUI responsive I should use the SwingWorker class to do the task in a separate thread. Ok so far.
No I have a model with around 15 methods that are remote methods. Each method returns different object type as a result than the others.
In my view the user presses a button and the appropriate method in the model is called. Without using the swingworker the GUI froze. My question is, am I supposed to create 15 subclasses of Swingworker threads and create a NEW instance of each as needed according to user's actions? Is my understanding correct? Is there a standard way for this or what I say is a correct approach?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看看这个:简单后台任务。
看来你有两个担忧。首先,关于使用
SwingWorker
时所需的代码量:您确实需要为每个操作创建SwingWorker
的子类,但这并不意味着它们需要位于顶部-级别、命名类或在它们自己的文件中。它们可以是匿名类,如本文所示,以便代码位于 GUI 的事件处理代码中。其次,关于
SwingWorker
对象的实例化:您不能重用SwingWorker
,但由于作业是由于用户活动(例如单击按钮)而执行的,每次实例化新对象时,您不应该遇到任何性能问题。Have a look at this: Simple Background Tasks.
It seems you have two concerns. Firstly, regarding the amount of code required when using
SwingWorker
: you do need to create a subclass ofSwingWorker
for each action, but that doesn't mean they need to be top-level, named classes, or in their own files. They can be anonymous classes, as shown in the article, so that the code is within your GUI's event-handling code.Secondly, regarding instantiation of
SwingWorker
objects: you can't reuse aSwingWorker
, but since the jobs are being executed as a result of user activity (e.g. clicking a button), you shouldn't encounter any performance problems with instantiating new objects each time.无论如何,SwingWorkers 都能完成工作。根据我的经验,我不喜欢仅使用 SwingWorkers 来完成一项小工作。我更喜欢生成一个线程,并让该线程请求 EventDispatch 线程更新 GUI。尽管有一些例外,但只有 EventDispatch 线程应该更新 UI。
我建议阅读 Swing 中的线程
虽然线程可能会变得很繁重,并且也许这个解决方案并不在所有情况下都适合您,但如果单独的线程需要引发 GUI 中的更改,请使用类似的东西,
By all means, SwingWorkers get the job done. In my experience, I haven't liked using the SwingWorkers for just one little job. I prefer to spawn off a thread, and have that thread ask the EventDispatch thread to update the GUI. Only the EventDispatch thread should update the UI, though there are a few exceptions.
I would suggest reading about threads in threads in Swing.
Though threading can get heavy, and maybe this solution would not work for you in all cases, if a seperate thread needs to spark a change in GUI, use something like,