×

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

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 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.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Series Program in Java

Series Program in Java The series program in Java is written to print the mathematical series such as the Fibonacci series, Pell series, etc. A few of the renowned series are...

12 minutes read.

Calculator Program in Java

Calculator Program in Java A calculator performs the basic mathematical operations such as addition, subtraction, multiplication, etc. In this section, we will create a calculator program in Java using switch case...

5 minutes read.

Rectangular Numbers in Java

In this tutorial, we will understand the meaning of a rectangular number in Java with the aid of examples, illustrations, and implementations. It is one of the popular coding interview...

3 minutes read.

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.

Differences between Byte Code and Machine Code

This tutorial will discuss the differences between Byte Code and Machine Code. Before that, let's try to know what byte and machine code is. Introduction Every computer has a set of instructions...

4 minutes read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.