Introduction To Swing In Java


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 of Swing

Siince 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:

  • lightweight
  • configurable
  • platform independent
  • customizable
  • extensible

Swing Hierarchy



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.


In this program we make a simple window without any extra features or functionality.

publicclass Example123extends JFrame
setTitle("Just a simple program of Java Swing"
        setSize(425, 350
publicstatic voidmain(String[]args)
        publicvoid run
            Example123esw =new Example123


When we run our program, a window will be generated that is like the following window:


java Example123



Swing has the following advantages over AWT:

  • Provides both additional functionality and added components to AWT-replacement components

  • Swing components are plateform independent.

  • Swing components can use a different look and feel.

  • Swing components use the Model-View-Controller paradigm (MVC), and thus can provide a much more flexible UI.

  • Swing components are lightweight (are less resource intensive than AWT).

  • Swing provides built-in double buffering.

  • Swing provides paint debugging support for when you build your own components.


Swing has a few disadvantages; they are:

  • it can be slower than AWT (all components are drawn) as if we're not careful in programming.

  • It requires Java 1.2 or a separate JAR file.

  • Swing components that look like native components might not act exactly like native components.

Up Next
    Ebook Download
    View all
    View all