What is Java Swing?

Swing in Java is a Graphical User Interface (GUI) toolkit that includes the GUI components. Swing provides a rich set of widgets and packages to make sophisticated GUI components for Java applications. Swing is a part of Java Foundation Classes(JFC), which is an API for Java programs that provide GUI.

The Java Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older, platform dependent GUI toolkit. You can use the Java GUI programming components like button, textbox, etc. from the library and do not have to create the components from scratch.

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.









Java Swing class Hierarchy Diagram




What is a Container Class?

Container classes are classes that can have other components on it. So for creating a Java GUI, we need at least one container object. There are 3 types of Java Swing containers.

  1. Panel: It is a pure container and is not a window in itself. The sole purpose of a Panel is to organize the components on to a window.

  2. Frame: It is a fully functioning window with its title and icons.

  3. Dialog: It can be thought of like a pop-up window that pops out when a message has to be displayed. It is not a fully functioning window like the Frame.

What is GUI in Java? GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for Java applications. It is mainly made of graphical components like buttons, labels, windows, etc. through which the user can interact with an application. GUI plays an important role to build easy interfaces for Java applications.



Java Swing Examples

Let's see a simple swing example where we are creating one button and adding it on the JFrame object inside the main() method.



File: FirstSwingExample.java

  1. import javax.swing.*;

  2. public class FirstSwingExample {

  3. public static void main(String[] args) {

  4. JFrame f=new JFrame(); //creating instance of JFrame

  5. JButton b=new JButton("click"); //creating instance of JButton

  6. b.setBounds(130,100,100, 40); //x axis, y axis, width, height

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

  8. f.setSize(400,500); //400 width and 500 height

  9. f.setLayout(null); //using no layout managers

  10. f.setVisible(true); //making the frame visible

  11. }

  12. }


OUTPUT:




 

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.




What we will learn in Swing?


  • JButton class

  • JRadioButton class

  • JTextArea class

  • JComboBox class

  • JTable class

  • JColorChooser class

  • JProgressBar class

  • JSlider class

  • Graphics in swing

  • OpenDialog Box

  • BorderLayout

  • GridLayout

  • FlowLayout

  • CardLayout

We will discuss these topics in our upcoming blogs.

Thank you for read this blog.


221 views0 comments