×

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features, and superior event handling with drag-and-drop support. The platform-independent "model-view-controller" Swing GUI framework for Java employs a single-threaded development style.

Additionally, this framework provides an abstraction layer between the Swing-based GUI's graphical presentation and code organization. Swing was created to offer an updated variety of GUI components compared to the previous Abstract Window Toolkit (AWT). Swing provides pluggable look and feel, which enables applications to have a look and feel that is independent of the underlying platform and that replicates the looks and feels of many platforms.

Introduction of Java Swing

The Java distribution standard includes Swing, which has almost four times as many User Interface [UI] components than AWT. By the standards of today's application GUI needs, AWT is a constrained implementation, unable to fully provide the components needed for creating the complex GUIs needed in contemporary business applications.

The AWT component set has several problems and consumes a lot of system resources as compared to similar Swing resources. Netscape introduced their Internet Foundation Classes [IFC] library for Java. Its classes immediately became quite popular with programmers creating GUIs for corporate applications.

  1. Swing is a set of API ( API- Set Of interfaces and classes )
  2. Swing is a tool for designing graphical user interfaces.
  3. Swing is an AWT Extension library (Abstract Window Toolkit)
  4. Contains New and Improved Components that have been Increasing the Appearance and Functionality of GUIs
  5. Swing may be used to create standalone swing GUI apps, as well as servlets and applets.
  6. Model-view architecture is employed.
  7. Swing, which is based on AWT, is more adaptive and movable than AWT.
  8. Swing was created fully in Java
  9. Java Swing Components are Small and Platform Independent
  10. Swing Offers Stronger Components and Supports a Pluggable Look and Feel.
  11. Tables, lists, scroll panes, colour selectors, tabbed panes, etc.
  12. More Swing Comes After MVC

Many programmers mistakenly believe that JFC and Swing are interchangeable, although this is not. Swing [A UI component package] is part of JFC, along with quite a few other things:

  • Cut and paste: support for the clipboard
  • Accessibility features: Designed to provide graphical user interfaces for individuals with impairments
  • Java 1.1 is where the Desktop Colors Features were first introduced.
  • Java 2D: It now supports better colours, pictures, and text.

Features of Swing Class

  • Platform Independent: Java is a platform-independent language and works on any client system, an application's GUI built using Swing components is unaffected by the GUI look and feel, which is controlled and provided by a platform-specific O/S.
  • Architecture: Uses MVC architecture.
  • Lightweight Components: Its AWT-supported lightweight component development is available as of JDK 1.1. A component must not depend on any non-Java [O/s based] system classes in order to be considered lightweight. Java's look and feel classes support the unique views of Swing components.
  • Pluggable Look and Feel: With the help of this functionality, users can change the appearance and feel of Swing components without having to restart an application. Wherever the program runs, the Swing library enables components that have a consistent look and feel. The Swing library offers an API that allows for significant customization of the GUI of an application.
  • Highly customizable: Due to the fact that external appearance is independent of internal representation, swing controls can be easily adjusted.
  • Rich controls: Swing has a wide range of sophisticated controls, including table, slider, colour picker, and Tree TabbedPane controls.

Swing Classes Hierarchy

Java Swings

The MVC Connection

  1. A visual component is typically a composite of three separate elements:
    • The display's rendering of the component's appearance
    • The manner in which a component responds to a user
    • The component's associated state information
  2. One component architecture has consistently demonstrated extraordinary effectiveness over time: Model-View-Controller, or just MVC.
  3. The model is equivalent to the state data connected to the component in MVC terminology.
  4. Any elements of the view that are impacted by the model's current state are taken into account when determining how the component will appear on the screen.
  5. How a component responds to the user is controlled by the controller.

The following Swing components have features that go well beyond AWT components:

  • In addition to or instead of text, swing buttons and labels may display graphics.
  • Most Swing components' boundaries can be simply modified. For instance, adding a 1 pixel border to the outside of a Swing label is simple.
  • Swing parts don't always have to be square. Round buttons are one type of button.
  • Now Screen readers and other modern assertive technologies can easily access information from Swing components. For instance: A Swing button or label's text can be easily captured by a screen reader program.

Example

Below is the java program to demonstrate java swing

import java.io.*;


import javax.swing.*;


// Main class


class Demo {


    // Main driver method


    public static void main(String[] args)


    {


JFrame f= new JFrame(); // making a JFrame instance


JButtonbu = new JButton(" click on javatpoint website"); // establishing a JB instance


b.setBounds(160, 210, 230,60); // x axis, y axis, w, h


f.add(b); // JFrame button adding


f.setSize(600, 700); // 600 width and 700 height


f.setLayout(null); // without utilizing layout managers


f.setVisible(true); // the frame being visible


    }


}

Output:

Java Swings

Components of Swing Class the Task’s Percentage                     

ClassDescription
ComponentThe abstract basis class for all of SWING's non-menu user interface controls is called a Component. Components are a graphical representation of an object.
ContainerA component called a "container" can hold SWING components.
JComponentJComponent serves as the foundation class for all swing UI Components. To utilise a swing component that derives from JComponent, a component must be in a containment hierarchy with a top-level Swing container as its root.
JColorChooserThe JColorChooser provides a control panel designed to allow the user to modify and select a colour.
JListThe user is represented by a JList component with a scrolling list of text items.
JRadioButtonThe JRadioButton class represents a visual (GUI) element having a on (true) or off (false) state. in the group
JCheckBoxA JCheckBox is a graphical (GUI) element that has two possible states: on (true) and off (false).
JTextAreaA text component that enables for the editing of many lines of text is called a JTextArea object.
JPasswordFieldIt is a JPasswordField object, a text component made exclusively for entering passwords.
JComboBoxA JComboBox component gives the user a show-up menu of options.
JSpinnerA user may select an object value or a number from an ordered list in the field of a JSpinner belonging to this class.
JFileChooserThe dialogue box that a JFileChooser it Controls depicts allows the user to choose a file
JScrollbarUsers can choose from a range of values by using a scroll bar component represented by a JScrollbar control.
ImagelconAn implementation of the icon interface that creates icons from images is called an imageicon control.
JLabelJLabels are object components used to add text to containers.
JButtonThis class develops a button with a label.
JTextFieldA text component called a JTextField object allows you to change a single line of text.
JSliderA JSlider of this type allows a user to visually (GUI) select a value by turning a knob over a finite range of values.
JProgressBarThe progress bar shows the task's percentage of completion as it gets closer to being finished.
JOptionPaneUsers are prompted for a value or Something in a collection of standard dialogue boxes provided by JOptionPane.

Window with Button

The software that follows is built using Swing. A window (a JFrame) with a label and a button is displayed.

import java.awt.FlowLayout;


import javax.swing.JButton;


import javax.swing.JFrame;


import javax.swing.JLabel;


import javax.swing.WindowConstants;


import javax.swing.SwingUtilities;


public class SE implements Runnable {


    public void run() {


        // Creating the window


JFramefm = new JFrame("Hello, !");


        //determines how the window should behave when it is closed.fm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);


        // Add a layout manager to prevent the button from being positioned over the label.


fm.setLayout(new FlowLayout());


        // Add a button and a label.


fm.add(new JLabel("java, tpoint!"));


fm.add(new JButton(" click !"));


        // Organize the window's components.


fm.pack();


        // The window is hidden by default. Make it obvious.


fm.setVisible(true);


    }


    public static void main(String[] args) {


SwingExampleSE = new SwingExample();


        // Schedules the execution of the programme in the event queue at the appropriate time.


SwingUtilities.invokeLater(SE);


    }


}

Output:

Java Swings

Keep in mind that each Swing component is handled by an instance of the class that implements the Runnable interface that is produced when the component is created. Then, using the method SwingUtilities.invokeLater(Runnable), which was created in the main function, this is carried out on the Event Dispatch Thread (see Swing and thread safety).

Calling resources from different threads might cause thread interference and memory consistency issues since Swing is not thread-safe. It is believed that employing this strategy is best practice, even if Swing code may be performed without it (for example, by removing Runnable and relocating all instructions from the run method to the main function).

import javax.swing.JFrame;


import javax.swing.JButton;


import javax.swing.JOptionPane;


import javax.swing.SwingUtilities;


import java.awt.event.ActionListener;


import java.awt.event.ActionEvent;


public class Demo extends JFrame {


          private final JButtonbu = new JButton();


          public Sample() {


                    super();


                    this.setTitle("Hello");


                    this.getContentPane().setLayout(null);


                    this.setBounds(110, 110, 190, 150);


                    this.add(makeButton());


                    this.setVisible(true);


                    this.setDefaultCloseOperation(EXIT_ON_CLOSE);


          }


          private JButtonmakeButton() {


                    bu.setText("Click me!");


                    bu.setBounds(50, 50, 110, 40);


                    bu.addActionListener(new ActionListener() {


                              public void actionPerformed(ActionEvent e) {


                                        JOptionPane.showMessageDialog(bu, "Hello World!");


                              }


                    });


                    return bu;


          }


          public static void main(String[] args) throws InvocationTargetException, InterruptedException {


                    // The event dispatching thread is required to execute Swing calls.


                    SwingUtilities.invokeAndWait(() -> new Sample());


          }


}

Output:

The layout is set to null using the Container.setLayout(LayoutManager) function because JFrame makes use of java.awt. By default, BorderLayout manages the layout. BorderLayout-added widgets are centred and expanded to provide room for any extra widgets. Of fact, most GUI applications would want to use a layout-manager instead of basing everything on absolute coordinates in the real world.


Related Topics

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

Java Worker Class

What is a Worker? A service which executes Work - flow and Activities is referred to as a Worker. On user-controlled hosts, workers are defined and put into action. The Worker...

3 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.

String Coding Interview Questions in Java

What is String in Java?In Java, a String is a Class that is defined in the java.lang package. It isn't a basic data type like int or long. Character Strings...

5 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

StringBuilder in Java

StringBuilder in Java Java StringBuilder class is introduced since JDK 1.5. The StringBuilder class is mainly used to create modifiable or mutable strings. Note that the StringBuilder class is not synchronized....

7 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to...

2 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.