lundi 15 mai 2023

What is a good design pattern for a Java Swing application with long calculations in EDT?

I aw writing a chess game application using Java Swing. My game logic is obviously turn-based. Here is a very simplified excerpt:

public class PanelBoard extends JPanel implements MouseListener
{
    @Override
    public void paintComponent(Graphics g)
    {
        //Painting the board.
        //Painting chess pieces.
    }
    @Override
    public void mouseReleased(MouseEvent e)
    {
        //Calculate selected coordinates on the board.
        //If a chess piece is selected, highlight this piece and its possible moves.
        //If a destination is selected, nove a chess piece.
        //Repaint the board.
    }
}

I have recently discovered that all Java Swing components should be accessed on Event Dispatch Thread. But it is also said that all event handling should be as short as possible in order not to block the GUI. My questions are:

  1. Let's imagine that my calculation of all possible moves of a chess piece is a very long operation. Then in the mouseReleased() method I can call SwingWorker.doInBackground() method to make a separate thread for my long calculation. But is this really necessary in my case with a turn-based approach? User input is not expected until the previous event has been handled.

  2. In what cases making a background thread to handle a long calculation is a viable strategy?

  3. If I understand correctly, there are currently two threads in my program: main thread and EDT. Why make a separate background thread to handle a long calculation if this calculation can be redirected to a main thread?

  4. How exactly can I redirect a long calculation to a main thread and what design pattern can be used in such case? I come from an embedded world, so the only thing that comes to my mind is a polling architecture. Let's say, for example, a main thread has an infinite loop that waits for a particular event in a queue. In my case it would be a request to process a long calculation from mouseReleased() method (delayed interrupt/event processing). But this way my main thread becomes a copy of EDT and practically does the same thing. Also I beleive this approach defeats the whole purpose of event-driven architecture.

  5. What are good design patterns for GUI applications in general?

Aucun commentaire:

Enregistrer un commentaire