Events in Swing

Events in Swing

My last article talks about events and one of the design patterns: Observer. Now, it is time to say valuable things about events in the Swing. This article is also available in Polish.

1. SWING

It is one of Java’s libraries to implement GUI (graphical user interface).  By using Swing applications are highly interactive and flexible regarding features. We can check that in the JetBrains application IntelliJ IDEA. In the community version, we can find below:

swing w Intelij IDEA
Swing in InteliiJ IDEA community

2. How events works?

Swing beyond events is based on action listeners from the AWT and Swing is newer version of AWT library. An „event handling” mechanism is worth paying attention to because it is responsible for managing events.This mechanism recognises and decides what should happen when a specific event occurs.  Please see a code example to understand it better.

KeyEvent: key press code.
KeyEvent: key press code. Resource: Devwords

When we press a specific keyboard key the code above calls a key event. Numbers: 38, 37, 39, and 40 are accordingly for: up, left, right and down arrows. Additionally, we can see on the terminal which key was pressed. Please see the below image:

Efekt eventu keyPress
Result of event keyPress. Resource: Devwords

 

Also, I prepared an example of an event called pressing the computer mouse. Please see below:

Efekt eventu keyPress.
Result of ActionEvent created by press the computer mouse on „Click me”. Resource: Devwords.

Effect:

Efekt eventu keyPress
Efekt eventu keyPress. Resource: Devwords

3. Sum up

On the one hand, „window applications” are highly interactive and flexible for users because of the Swing library. For example, it can be IntelliJ IDEA, which has plenty of features that help in the nowadays programming.
On the other hand, Swing is not as popular as other front-end frameworks such as React or Angular. Nevertheless, it is worth knowing Swing and events, and how they work together. It helps us to understand better more advanced matters.

 

 

4 thoughts on “Events in Swing”

  1. Hej dziękuję za ten artykuł był on moją inspiracją do stworzenia projektu zaliczeniowego. Możesz powiedzieć jak z wykorzystaniem swinga stworzyć analogowy zegar? Powinienem użyć wątków? A może wątków z Javy 21 ?

    1. Hej 🙂 dziękuje za komentarz. Aby zaimplementować analogowy zegar powinieneś użyć 3 wątków odpowiedni dla godzin, minut i sekund. 🙂

        1. W sytuacji, gdy kilka wątków operuje na jednej i tej samej zmiennej, każdy z tych wątków może przechowywać kopię tej wartości w cache-u. Jeżeli więc wątek A zmieni wartość zmiennej, wątek B może tego nie zobaczyć. Rozwiązaniem jest użycie modyfikatora volatile, dzięki czemu Java, tworząc daną zmienną wie, aby nie umieszczać jej w cache-u.

Leave a Comment

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *