Java Swing Tutorial
Java Swing is built on AWT(Abstract Window ToolKit).
Differences between Swing and AWT
- Swing is platform independent whereas AWT its dependent.
- Swing is lightweight whereas AWT is heavyweight.
- Swing supports Look And Feel that can be plugged whereas AWT does not.
- AWT has fewer components compared to Swing.
- Swing follows Model View Controller whereas AWT does not.
Java Swing Class Hierarchy
Commonly used methods in Swing classes
- [ void add(Component c)]-add component to another.
- [void setSize(int w,int h)]-sets component height and width.
- [void setLayout(LayoutManager l)]-determines how component are displayed.
- [void setVisible(boolean )]-makes component visible.Set by default false.
Java Swing JFrame Example
[
import javax.swing.JFrame; import javax.swing.JButton; public class FirstSwingExample { public static void main(String args[]) { JFrame frame=new JFrame("JFrame example"); JButton button=new JButton("Click ME"); button.setBounds(50,50,100,30); frame.add(button); frame.setLayout(null); frame.setSize(400,400); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
]
There are two ways of creating JFrame class.
- One is by extending JFrame class(Inheritance).
- Creating JFrame object (association).
Java Swing JFrame Inheritance Example
[
import javax.swing.JFrame; import javax.swing.JButton; public class FirstSwingExample extends JFrame{ FirstSwingExample() { super("Jframe Example"); JButton button=new JButton("Click ME"); button.setBounds(50,50,100,30); add(button); setLayout(null); setSize(400,400); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String args[]) { new FirstSwingExample(); } }
]
Java Swing JFrame Association Example
[
import javax.swing.JFrame; import javax.swing.JButton; public class FirstSwingExample { FirstSwingExample() { JFrame frame=new JFrame("JFrame example");//creates JFrame instance JButton button=new JButton("Click ME");//creates JButton class button.setBounds(50,50,100,30);//positions button on JFrame frame.add(button);//adds JButton to the JFrame frame.setLayout(null);//sets layout frame.setSize(400,400);//sets JFrame Size frame.setLocationRelativeTo(null);//centers the Jframe at the center of the screen frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static void main(String args[]) { new FirstSwingExample(); } }
]