GUI level vs Code layer vs Swing

I have always coded console applications and learned some basic UML / template skills using C ++.

Now I decided to switch to Java and add graphical interfaces to my programs.

The first question is how to handle the GUI layer in a program. I mean, how should I separate all the GUI code (adding components, handling main events) with the code that really does the job (for example, when you click a button).

Another issue related to EDT. I read that (almost) all Swing components must run on the same thread (usually EDT) due to the fact that they are not thread safe. Therefore, I thought that if he called "heavy code" (for example) ActionListener , then the graphical interface will stop responding for a while until the "heavy code" ends.

This is rather undesirable, so I think that the natural solution is to run heavy code, perhaps in a different thread or something like this (I know that this should be done carefully, because I could no longer assume that after the user clicked the button , "deep action" is performed before accessing another graphical interface).

So, as you can see, I have a lot of questions about how to include a graphical interface in my templates in order to keep everything completely independent and easily maintained; and some questions about specific things about Swing components and responsiveness.

+4
source share
2 answers

Undo the business logic from the GUI: if you intend to use Swing, first look at the Model-View-Controller design pattern. This is a good model for separation of interests, and Swing relies heavily on this.

Enter enhanced security code and EDT: use SwingUtilities or even better SwingWorkers .

+3
source

You will see that Swing is already heavily structured into an MVC option, which they call view-delegate.
What you will need to do is decide how much application logic goes into the GUI layer, and there are always some. One thing that helps is that if the gui action is designed to perform an important task - for example, updating some data in the database, then make sure there is a simple call that can invoke a GUI action handler that has nothing to do with gui code / structure. This can be accomplished using projects in your IDE that have a one-way dependency. For example, save your entire GUI in a "gui" project, which depends on your "general" project. A โ€œnormalโ€ project will be able to execute business logic, but it will not import widgets and cannot see your gui project.

It's good that you have identified EDT as a key design issue - because it is. SwingWorker has already been proposed by LBT, which is a good way to manage long-term gui tasks in a separate thread.

+1
source

All Articles