Introduction

In this article, we discuss Java Swing as used for "Graphics programming in Java". We discuss the basic classes of Swing, why we use it, its advantages and a comparison with AWT.

Swing in Java

It is a Java Graphical User Interface (GUI) toolkit. It is an Application Programming Interface (API) for providing a Graphical User Interface (GUI) for Java programs.
It is a part of the JFC (Java Foundation Classes), that is an API for providing a graphical user interface for Java programs.
It is used to create a GUI with Java.
Need for Swing
Since we already have a class AWT for a GUI, why do we need Swing for GUI? Here are some points that describe the need of Swing:

Swing Hierarchy

Swing Hierarchy

Swing Packages

The main packages in swing are:
  1. javax.swing.text
  2. javax.swing.plaf.multi
  3. javax.swing.text.html
  4. javax.swing.text.html.parser
  5. javax.swing.text.rtf
  6. javax.swing.tree
  7. javax.swing.undo
  8. javax.accessibility
  9. javax.swing
  10. javax.swing.border
  11. javax.swing.colorchooser
  12. javax.swing.event
  13. javax.swing.filechooser
  14. javax.swing.plaf
  15. javax.swing.plaf.basic
  16. javax.swing.plaf.metal
  17. javax.swing.plaf.synth
  18. javax.swing.table
It is an update GUI toolkit. It adds various components to our window frame like lables, buttons, scrollbars, tables and trees.
Example
In this program we make a simple window without any extra features or functionality.
  1. importjavax.swing.JFrame;
  2. importjavax.swing.SwingUtilities;
  3. publicclass Example123extends JFrame
  4. {
  5. publicExample123()
  6. {
  7. setTitle("Just a simple program of Java Swing");
  8. setSize(425, 350 );
  9. setLocationRelativeTo(null);
  10. setDefaultCloseOperation(EXIT_ON_CLOSE);
  11. }
  12. publicstatic voidmain(String[]args)
  13. {
  14. SwingUtilities.invokeLater(newRunnable()
  15. {
  16. publicvoid run()
  17. {
  18. Example123esw =new Example123();
  19. esw.setVisible(true);
  20. }
  21. });
  22. }
  23. }
Output
When we run our program, a window will be generated that is like the following window:
javac Example123.java
java Example123
pic-1.jpg

Advantages of Swing

Swing has the following advantages over AWT:

Disadvantages of Swing

Swing has a few disadvantages, they are: