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 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
Packages
The main packages in swing are:
- javax.swing.text
- javax.swing.plaf.multi
- javax.swing.text.html
- javax.swing.text.html.parser
- javax.swing.text.rtf
- javax.swing.tree
- javax.swing.undo
- javax.accessibility
- javax.swing
- javax.swing.border
- javax.swing.colorchooser
- javax.swing.event
- javax.swing.filechooser
- javax.swing.plaf
- javax.swing.plaf.basic
- javax.swing.plaf.metal
- javax.swing.plaf.synth
- 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.
importjavax.swing.JFrame;
importjavax.swing.SwingUtilities;
publicclass Example123extends JFrame
{
publicExample123()
{
setTitle("Just a simple program of Java Swing");
setSize(425, 350 );
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
publicstatic voidmain(String[]args)
{
SwingUtilities.invokeLater(newRunnable()
{
publicvoid run()
{
Example123esw =new Example123();
esw.setVisible(true);
}
});
}
}
Output
When we run our program, a window will be generated that is like the following window:
javac Example123.java
java Example123
Advantages
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.
Disadvantages
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.