ognawtswings
ognawtswings
• Advantages of Applet
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many
platforms, including Linux, Windows, Mac Os etc.
• Hierarchy of Applet:
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and
java.awt.Component class provides 1 life cycle methods for an
applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be
inherited. It provides 4 life cycle methods of applet:
public void init(): is used to initialize the Applet. It is invoked
only once.
public void start(): is invoked after the init() method or
browser is maximized. It is used to start the Applet.
public void stop(): is used to stop the Applet. It is invoked
when Applet is stop or browser is minimized.
public void destroy(): is used to destroy the Applet. It is
invoked only once.
java.awt.Component class:
//First.java myapplet.html
import java.applet.Applet; <html>
import java.awt.Graphics; <body>
public class First extends Applet <applet code="First.class" width="300"
{ height="300">
public void paint(Graphics g) </applet>
{ </body>
g.drawString("welcome",150,150); </html>
}
}
How to run an Applet?
Simple example of Applet by appletviewer tool :
To execute the applet by appletviewer tool, create an applet that
contains applet tag in comment and compile it. After that run it
by: appletviewer First.java. Now Html file is not required but it is
for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java.
Components
• All the elements like the button, text fields, scroll bars, etc. are called
components.
• In Java AWT, there are classes for each component as shown in above diagram.
Container
• The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
• It is basically a screen where the where the components are placed at their
specific locations. Thus it contains and controls the layout of components.
There are four types of containers in Java AWT:
• Window: The window is the container that have no borders and menu
bars
• Panel: The Panel is the container that doesn't contain title bar, border or
menu bar. It is generic container for holding the components. It can have
other components like button, text field etc.
• Frame: The Frame is the container that contain title bar and border and
can have menu bars. It can have other components like button, text field,
scrollbar etc. Frame is most widely used container while developing an
AWT application.
• Dialog
.Method Description
// creating a button
Button b = new Button("Click Me!!");
// no layout manager
setLayout(null);
// main method
public static void main(String args[]) {
}
AWT Example by Association
// creating a Frame
Frame f = new Frame();
// creating a Label
Label l = new Label("Employee id:");
// creating a Button
Button b = new Button("Submit");
// creating a TextField
TextField t = new TextField();
// setting position of above components in the frame
l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);
// no layout
f.setLayout(null);
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener
{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
myapplet.html
add(b);add(tf);
b.addActionListener(this); <html>
setLayout(null); <body>
} <applet code="EventApplet.class"
public void actionPerformed(ActionEvent e) width="300" height="300">
{ </applet>
tf.setText("Welcome"); </body>
} </html>
}
Painting in Applet
Perform painting operation in applet by the
mouseDragged() method of
import java.awt.*; MouseMotionListener.
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet
implements MouseMotionListener
{
public void init(){
addMouseMotionListener(this);
setBackground(Color.red);
}
We can get any information from the HTML file as a parameter. For this purpose,
Applet class provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)
l = new Label();
l.setBounds(50, 100, 250, 20);
// main method
public static void main(String[] args) {
new LabelExample2();
}
AWT TextArea Example with ActionListener
import java.awt.*;
import java.awt.event.*;
// our class extends the Frame class to inherit its properties
// and implements ActionListener interface to override its methods
public class TextAreaExample2 extends Frame implements ActionListener {
// creating objects of Label, TextArea and Button class.
Label l1, l2;
TextArea area;
Button b;
// constructor to instantiate
TextAreaExample2() {
// instantiating and setting the location of components on the frame
l1 = new Label();
l1.setBounds(50, 50, 100, 30);
l2 = new Label();
l2.setBounds(160, 50, 100, 30);
area = new TextArea();
area.setBounds(20, 100, 300, 300);
b = new Button("Count Words");
b.setBounds(100, 400, 100, 30);
// class constructor
ChoiceExample2() {
// creating a frame
Frame f = new Frame();
// creating a button
Button b = new Button("Show");
// main method
public static void main(String args[])
{
new ChoiceExample2();
}
}
AWT List Example with ActionListener
// creating the 2 list objects of 4 rows
// adding items to the list using add()
// setting location of list components
final List l1 = new List(4, false);
l1.setBounds(100, 100, 70, 70);
l1.add("C");
l1.add("C++");
l1.add("Java");
l1.add("PHP");
//If the value of multipleMode is true, then the user can select multiple items from
the list. If it is false, only one item at a time can be selected.
final List l2=new List(4, true);
l2.setBounds(100, 200, 70, 70);
l2.add("Turbo C++");
l2.add("Spring");
l2.add("Hibernate");
l2.add("CodeIgniter");
// main method
public static void main(String args[])
{
new ListExample2();
}
}
The Canvas class controls and represents a blank rectangular area where the
application can draw or trap input events from the user. It inherits the Component
class.
import java.awt.*;
// creating a frame
Frame f = new Frame("Canvas Example");
// adding canvas to frame
f.add(new MyCanvas());
// adding specifications
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
Java AWT Scrollbar Example with AdjustmentListener
import java.awt.*;
import java.awt.event.*;
// class constructor
ScrollbarExample2() {
// creating a Frame with a title
Frame f = new Frame("Scrollbar Example");
// main method
public static void main(String args[]){
new ScrollbarExample2();
}
}
• The object of MenuItem class adds a simple labeled menu item on menu. The
items used in a menu must belong to the MenuItem or any of its subclass.
import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}
Java Swing
Java Swing is 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.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
No. Java AWT Java Swing
}
public static void main(String[] args) {
DisplayGraphics m=new DisplayGraphics();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);
//f.setLayout(null);
f.setVisible(true);
}
}
Jbutton
JLabel
JTextField
JTextArea
JPasswordField
JCheckBox
JRadioButton
JComboBox
Jtable
JList
JOptionPane
JOptionPane
showMessageDialog()
import javax.swing.*;
public class OptionPaneExample
{
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Hello, Welcome to Javatpoint.");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
JOptionPane
import javax.swing.*;
showInputDialog()
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
String name=JOptionPane.showInputDialog(f,"Enter Name");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
showConfirmDialog()
import javax.swing.*;
import java.awt.event.*;
public class OptionPaneExample extends WindowAdapter{
JFrame f;
OptionPaneExample(){
f=new JFrame();
f.addWindowListener(this);
f.setSize(300, 300);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setVisible(true);
}
public void windowClosing(WindowEvent e) {
int a=JOptionPane.showConfirmDialog(f,"Are you sure?");
if(a==JOptionPane.YES_OPTION){
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public static void main(String[] args) {
new OptionPaneExample();
}
}
JScrollBar
JPopupMenu
Example of BorderLayout class: Using
import java.awt.*; BorderLayout() constructor
import javax.swing.*;
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as
CENTER
f.setLayout(new BorderLayout());
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
import java.awt.*; BorderLayout class: Using BorderLayout
import javax.swing.*; (int hgap, int vgap) constructor
public class BorderLayoutExample
{
JFrame jframe;
// constructor
BorderLayoutExample()
{
// creating a Frame
jframe = new JFrame();
// create buttons
JButton btn1 = new JButton("NORTH");
JButton btn2 = new JButton("SOUTH");
JButton btn3 = new JButton("EAST");
JButton btn4 = new JButton("WEST");
JButton btn5 = new JButton("CENTER");
// creating an object of the BorderLayout class using
// the parameterized constructor where the horizontal gap is 20
// and vertical gap is 15. The gap will be evident when buttons are placed
// in the frame
jframe.setLayout(new BorderLayout(20, 15));
jframe.add(btn1, BorderLayout.NORTH);
jframe.add(btn2, BorderLayout.SOUTH);
jframe.add(btn3, BorderLayout.EAST);
jframe.add(btn4, BorderLayout.WEST);
jframe.add(btn5, BorderLayout.CENTER);
jframe.setSize(300,300);
jframe.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new BorderLayoutExample();
}
}
Example of GridLayout class: Using GridLayout() Constructor
import java.awt.*;
import javax.swing.*;
// constructor
GridLayoutExample()
{
frameObj = new JFrame();
// creating 9 buttons
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
// adding buttons to the frame
// since, we are using the parameterless constructor, therfore;
// the number of columns is equal to the number of buttons we
// are adding to the frame. The row count remains one.
frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new GridLayoutExample();
}
}
GridLayout class: Using GridLayout(int rows, int columns) Constructor
import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
// adding buttons to the frame
f.add(b1); f.add(b2); f.add(b3);
f.add(b4); f.add(b5); f.add(b6);
f.add(b7); f.add(b8); f.add(b9);
GridLayout class: Using GridLayout(int rows, int columns) Constructor
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class FileChooserExample extends JFrame implements ActionListener{
JMenuBar mb;
JMenu file;
JMenuItem open;
JTextArea ta;
FileChooserExample(){
open=new JMenuItem("Open File");
open.addActionListener(this);
file=new JMenu("File");
file.add(open);
mb=new JMenuBar();
mb.setBounds(0,0,800,20);
mb.add(file);
ta=new JTextArea(800,800);
ta.setBounds(0,20,800,800);
add(mb);
add(ta);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==open){
JFileChooser fc=new JFileChooser();
int i=fc.showOpenDialog(this);
if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
String filepath=f.getPath();
try{
BufferedReader br=new BufferedReader(new FileReader(filepath));
String s1="",s2="";
while((s1=br.readLine())!=null){
s2+=s1+"\n";
}
ta.setText(s2);
br.close();
}catch (Exception ex) {ex.printStackTrace(); }
}}}
public static void main(String[] args) {
FileChooserExample om=new FileChooserExample();
om.setSize(500,500);
om.setLayout(null);
om.setVisible(true);
om.setDefaultCloseOperation(EXIT_ON_CLOSE);
}}
MouseListener Interface
MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event
package. It has five methods.
MouseListener Example
MouseListenerExample2
MouseMotionListener Interface
MouseMotionListenerExample
Paint
KeyListener Interface
Java KeyListener is notified whenever you change the state of key. It is notified
against KeyEvent. The KeyListener interface is found in java.awt.event package,
and it has three methods.
KeyListenerExample
KeyListenerExample2
WindowListener Interface
Java WindowListener is notified whenever you change the state of window. It is
notified against WindowEvent. The WindowListener interface is found in
java.awt.event package.
AdapterExample
MouseAdapterExample
MouseMotionAdapterExample
KeyAdapterExample
How to close AWT Window in Java
We can close the AWT Window or Frame by calling dispose() or System.exit() inside
windowClosing() method. The windowClosing() method is found in WindowListener
interface and WindowAdapter class.
If you implement the WindowListener interface, you will be forced to override all the
7 methods of WindowListener interface. So it is better to use WindowAdapter class.
AdapterExample
WindowExample3
JTabbedPane
TabbedPaneExample
JSlider
Puzzle Game
Puzzle Game
BallWorld game
Online Exam
PinBall game
TicTacToe game
Calculator