1

O java possui as classes homônimas javax.swing.Timer e java.util.Timer. Entendo que a primeira talvez tenha algum tipo de funcionamento especifico para a API swing, e cheguei a pensar que ela estendesse a segunda, mas isso não ocorre, conforme documentação.

Qual a diferença entre as duas classes? O fato de eu usar util.Timer numa aplicação gráfica com ou a swing.Timer num código que não faz uso da API gráfica pode ocasionar algum problema de compatibilidade?

2

1 Resposta 1

1

A grande diferença é que o javax.swing.Timer executa sua tarefa na Thread de eventos (EDT = Event Dispatch Thread). Portanto é indicado para manipular componentes da GUI.

O java.util.Timer usa uma Thread normal para executar suas tarefas. Cada instância do Timer cria a própria Thread.

A documentação do Timer da swing explica isso, só não muito fácil de entender (na minha opinião):

Although all Timers perform their waiting using a single, shared thread (created by the first Timer object that executes), the action event handlers for Timers execute on another thread -- the event-dispatching thread. This means that the action handlers for Timers can safely perform operations on Swing components. However, it also means that the handlers must execute quickly to keep the GUI responsive.

In v 1.3, another Timer class was added to the Java platform: java.util.Timer. Both it and javax.swing.Timer provide the same basic functionality, but java.util.Timer is more general and has more features. The javax.swing.Timer has two features that can make it a little easier to use with GUIs. First, its event handling metaphor is familiar to GUI programmers and can make dealing with the event-dispatching thread a bit simpler. Second, its automatic thread sharing means that you don't have to take special steps to avoid spawning too many threads. Instead, your timer uses the same thread used to make cursors blink, tool tips appear, and so on.

Problemas:

1) usar java.util.Timer com Swing: os métodos das componentes Swing devem ser chamados na Thread EDT, o que não ocorre (automaticamente) com esse Timer.

2) usar javax.swing.Timer com elementos não Swing: vai ser um problema se as operações forem demoradas pois eventualmente irão bloquear a interface gráfica.

Você deve fazer log-in para responder a esta pergunta.