AWT and Swing
Working with Frame class:-
import java.awt.*;
class Myframe extends Frame
{
Myframe()
{
FlowLayout layout = new FlowLayout();
setLayout(layout);
Button ok = new Button("OK");
Button cancel = new Button("Cancel");
add(ok);
add(cancel);
addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
dispose();
}
});
}
}
class ExtendingFrameClass
{
public static void main(String args[])
{
Myframe frame = new Myframe();
frame.setTitle("Extending Frame Class in Java Example");
frame.setSize(350,150);
frame.setVisible(true);
}
}
Advantages of Swing over AWT:-
AWT SWING
The AWT Component classes are provided The Swing component classes are provided
by the java.awt package by the javax.swing package.
The Components used in AWT are mainly The Components used in Swing are not
dependent on the operating system. They dependent on the operating system. It is
are platform dependent. completely scripted in Java. They are
platform independent.
The AWT is heavyweight since it uses the The Swing is mostly lightweight since it
resources of the operating system. doesn't need any Operating system object
for processing. The Swing Components are
built on the top of AWT.
The Appearance of AWT Components is The Swing Components are configurable
mainly not configurable. It generally depends and mainly support pluggable look and feel.
on the operating system's look and feels.
The Java AWT provides a smaller number of Java Swing provides a greater number of
components in comparison to Swing components than AWT, such as list, scroll
panes, tables, color choosers, etc
Java AWT needs a higher amount of Java Swing needs less memory space as
memory for the execution. compared to Java AWT.
Java AWT is slower than swing in terms of Java Swing is faster than the AWT.
performance.
Working with Swing:
1) JApplet:-
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);
add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
Note: JApplet class extends Applet class, so it holds methods of Applet class.
2) JFrame:-
import javax.swing.*;
import java.awt.*;
class JFrameClassExample extends JFrame
{
JFrameClassExample()
{
FlowLayout layout = new FlowLayout();
setLayout(layout);
JButton ok = new JButton("OK");
JButton cancel = new JButton("Cancel");
add(ok);
add(cancel);
}
}
class JFrameClassJavaExample
{
public static void main(String args[])
{
JFrameClassExample frame = new JFrameClassExample();
frame.setTitle("JFrame Class in Java Example");
frame.setBounds(200,250,350,150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}