Why AWT components are heavy-weight while Swing components are light-weight in Java?


  • AWT stands for Abstract Window ToolKit and it supports Java GUI programming. It is a portable GUI library for Stand-alone Java applications/applets. The AWT provides the connection between our application and the native GUI while Java Swing implements a set of GUI components that build on AWT technology and it can provide a pluggable look and feel. Java Swing is implemented entirely in the Java programming language.
  • First of all, by a heavy-weight, it means the code will take comparatively more time to load and it will consume more System resources. AWT is considered to be heavy-weight because its components are dependent on the underlying Operating System. For instance, When we create an object of java.awt.Checkbox class, its underlying Operating System will generate a checkbox for us. This is also the reason, AWT components are platform dependent.
  • On the other hand, most of the Java Swing components are implemented in Java itself. Some of the top level components like windows are dependent on the Operating System. But still, the overall program is comparatively light-weight than AWT.
  • Java Swing is the advanced and optimized version of AWT and it is built on top of AWT. Still, many AWT classes are used in Swing either directly or indirectly. It is important to do the basics of AWT before proceeding to Java Swing. Otherwise, we cannot understand the underlying facts about several control delegations while GUI in Java.

Example

import javax.swing.SwingUtilities;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class Test {
   public static void main(String[] args) {
      ApplicationWindow window = new ApplicationWindow();
      window.setVisible(true);
   }
}
class ApplicationWindow extends JFrame {
   public ApplicationWindow() {
      this.setSize(200, 100);
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.setLayout(new FlowLayout());
      Button exitButton = new Button("Exit");
      exitButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent event) {
            System.exit(0);
         }
      });
      this.add(exitButton);
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("Overlapping Menu");
      JMenuItem menuItem = new JMenuItem("Overlapping Item");
      menu.add(menuItem);
      menuBar.add(menu);
      this.setJMenuBar(menuBar);
      this.validate();
   }
}

Output

Updated on: 06-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements