Java Swing
Prepared By: Dimple Bohra
What is Swing in JAVA?
• Java Swing is a part of Java Foundation Classes (JFC) that is used
to create window-based applications.
• It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
What is Swing in JAVA?
• UnlikeAWT, Java Swing provides platform-independent and
lightweight components.
• The javax.swing package provides classes for java swing API such
as JButton, JTextField, JTextArea, JRadioButton, JCheckbox,
JMenu, JColorChooser etc.
JAVA Swing class hierarchy
Java Swing Containers
Top level Containers
•It inherits Component and Container of AWT.
•It cannot be contained within other containers.
•Heavyweight.
•Example: JFrame, JDialog, JApplet
Java Swing Containers
Lightweight Containers
•It inherits JComponent class.
•It is a general purpose container.
•It can be used to organize related components together.
•Example: JPanel
Difference between AWT and Swing
Commonly used methods of component class
How to create frame?
• There are two ways to create a frame:
• By creating the object of Frame class (association)
• By extending Frame class (inheritance)
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
add(b);//adding button on frame
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new Simple2();
}}
Swing features
• LightWeight − Swing components are independent of native Operating
System's API as Swing API controls are rendered mostly using pure JAVA code
instead of underlying operating system calls.
• Rich Controls − Swing provides a rich set of advanced controls like Tree,
TabbedPane, slider, colorpicker, and table controls.
• Highly Customizable − Swing controls can be customized in a very easy way as
visual appearance is independent of internal representation.
• Pluggable look-and-feel − SWING based GUI Application look and feel can be
changed at run-time, based on available values.