Slide 1
Slide 2
Slide 3

Label in java programming (V75)

No Comments

 

Lesson 8:                 Using Swing Controls

Every user interface considers three important aspects:

  • UI Elements – These are the visual components that users can see and interact with. Swing provides a large set of commonly used elements, ranging from basic to complex, which will be discussed in this lesson.
  • Layouts – These define how UI elements are arranged on the screen and provide the final look and feel of the GUI (Graphical User Interface).
  • Behavior – These are the events that occur when users interact with the UI elements.


Class Description
Component An abstract base class for non-menu user interface controls in Swing. A Component represents an object that has a graphical representation.
Container A component that can contain other Swing components.
JComponent A base class for all Swing UI components. To use a Swing component that inherits from JComponent, it must be part of a containment hierarchy whose root is a top-level Swing container.

1. SWING UI Elements

UI elements are called components (graphical elements) and containers (which hold components). These elements work together within layout managers (such as BorderLayout, FlowLayout, GridLayout, etc.) that determine how components are arranged.

1.1. JLabel

A Label in AWT is a GUI component that displays a non-editable text string to the user. It is mainly used to describe other components such as text fields or simply to display information.

Example:


Source Code:

Copied! 
   public ClockForm() {
        initComponents();
        // Start a thread to update Cambodia time every second
        Thread clockThread = new Thread(() -> {
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd MMM yyyy, hh:mm:ss a");
            sdf.setTimeZone(java.util.TimeZone.getTimeZone("Asia/Phnom_Penh")); // Cambodia timezone

            while (true) {
                clockLabel.setText("Time (Cambodia): " + sdf.format(new java.util.Date()));
                try {
                    Thread.sleep(1000); // update every second
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        clockThread.start();
    }                                                                                     

Result:


Watch the video:


Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

back to top