问题
What is the best way to handle GUi/ internal application communication. I have many underlying threads processing data, and would like to post their output to the gui.
Should I have some kind of handler object that is owned by all my runnables, and then have them post to it, so it can handle the output to the gui?
回答1:
I usually use an observer pattern for that kind of communication. So basically your thread classes implement a common interface (addObserver()) making them observables and your GUI controller/view implements the observer interface (fireNewEvent()) . If a thread has produced some kind of new content, it calls a method on the observer. Depending on your project the information to be presented can be pushed to the observer (e.g. fireNewEvent(Event e)) or the observer can access the information on its own (pull). Basically this is your idea plus the flexibility of notifying more than one observer (if needed).
回答2:
If you're using threads to avoid freezing the UI while executing long tasks, SwingWorker can help you.
来源:https://stackoverflow.com/questions/6888896/gui-application-communication