0% found this document useful (0 votes)
7 views83 pages

ognawtswings

Java Applets are embedded programs that run in a browser to create dynamic content, offering advantages like reduced response time and cross-platform compatibility. The lifecycle of an applet includes initialization, starting, painting, stopping, and destruction, with specific methods provided for each stage. Additionally, Java AWT is used for creating graphical user interfaces, with components like buttons and text fields, and event handling capabilities for user interactions.

Uploaded by

aditi21paul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views83 pages

ognawtswings

Java Applets are embedded programs that run in a browser to create dynamic content, offering advantages like reduced response time and cross-platform compatibility. The lifecycle of an applet includes initialization, starting, painting, stopping, and destruction, with specific methods provided for each stage. Additionally, Java AWT is used for creating graphical user interfaces, with components like buttons and text fields, and event handling capabilities for user interactions.

Uploaded by

aditi21paul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Java Applet

• Applet is a special type of program that is embedded in the


webpage to generate the dynamic content. It runs inside the
browser and works at client side.

• 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: Applet class extends Panel. Panel class


extends Container which is the subclass of Component.
Java Applet

• 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:

• The Component class provides 1 life cycle method of


applet.
• public void paint(Graphics g): is used to paint the Applet. It
provides Graphics class object that can be used for drawing
oval, rectangle, arc etc.

How to run an Applet?


There are two ways to run an applet
• By html file.
• By appletViewer tool (for testing purpose).
How to run an Applet?

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile


it. After that create an html file and place the applet code in html
file. Now click the html file.

//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{

public void paint(Graphics g){


g.drawString("welcome to applet",150,150);
}
}
To execute the applet, write in command /*
prompt: <applet code="First.class" width="300"
height="300">
c:\>javac First.java </applet>
c:\>appletviewer First.java */
Displaying Graphics in Applet
java.awt.Graphics class provides many methods for graphics
programming. Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
Displaying Graphics in Applet
10. public abstract void setColor(Color c): is used to set the graphics current color to
the specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to
the specified font.
import java.applet.Applet;
import java.awt.*;

public class GraphicsDemo extends Applet


{ myapplet.html
public void paint(Graphics g)
{ g.setColor(Color.red); <html>
g.drawString("Welcome",50, 50); <body>
g.drawLine(20,30,20,300); <applet code="GraphicsDemo.class"
g.drawRect(70,100,30,30); width="300" height="300">
g.fillRect(170,100,30,30); </applet>
g.drawOval(70,200,30,30); </body>
g.setColor(Color.pink); </html>
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}}
Displaying Image in Applet
Applet is mostly used in games and animation. For this purpose
image is required to be displayed. The java.awt.Graphics class
provide a method drawImage() to display the image.

Syntax of drawImage() method:


public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer):
is used draw the specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage() method that
returns the object of Image.
Syntax:
public Image getImage(URL u, String image){}
Other required methods of Applet class to display image:
public URL getDocumentBase(): is used to return the URL of the document in
which applet is embedded.
public URL getCodeBase(): is used to return the base URL.
import java.awt.*;
myapplet.html
import java.applet.*;
public class DisplayImage extends Applet { <html>
Image picture; <body>
public void init() { <applet
picture = getImage(getDocumentBase(),"sonoo.jpg"); code="DisplayImage.class"
} width="300" height="300">
public void paint(Graphics g) { </applet>
g.drawImage(picture, 30,30, this); </body>
} </html>
}
In the above example, drawImage() method of Graphics class is used to display
the image. The 4th argument of drawImage() method of is ImageObserver object.
The Component class implements ImageObserver interface. So current class
object would also be treated as ImageObserver because Applet class indirectly
extends the Component class.
Applet is mostly used in games and
import java.awt.*; animation. For this purpose image is
import java.applet.*; required to be moved.
public class AnimationExample extends Applet
{
Image picture;
public void init()
{
picture =getImage(getDocumentBase(),"bike_1.gif");
}
public void paint(Graphics g)
{
for(int i=0;i<500;i++)
{
g.drawImage(picture, i,30, this); myapplet.html
try{Thread.sleep(100);}
catch(Exception e){} <html>
} <body>
} <applet code="DisplayImage.class"
} width="300" height="300">
</applet>
</body>
</html>
AWT (Abstract Window Toolkit)

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.

• In order to place every component in a particular position on a screen, we need to


add them to a container.

Container

• The Container is a component in AWT that can contain another components


like buttons, textfields, labels etc.

• 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

public void add(Component c) Inserts a component on this component.


public void setSize(int width,int height) Sets the size (width and height) of the
component.
public void setLayout(LayoutManager m) Defines the layout manager for the
component.
public void setVisible(boolean status) Changes the visibility of the component, by
default false.
There are two ways to create a GUI using Frame in AWT.
• By extending Frame class (inheritance)
• By creating the object of Frame class (association)

// importing Java AWT class


import java.awt.*;

// extending Frame class to our class AWTExample1


public class AWTExample1 extends Frame {

// initializing using constructor


AWTExample1() {

// creating a button
Button b = new Button("Click Me!!");

// setting button position on screen


The setBounds(int x-axis, int y-axis, int
b.setBounds(30,100,80,30);
width, int height) method is used in the
above example that sets the position of
// adding button into frame
the awt button.
add(b);
// frame size 300 width and 300 height
setSize(300,300);

// setting the title of Frame


setTitle("This is our basic AWT example");

// no layout manager
setLayout(null);

// now frame will be visible, by default it is not visible


setVisible(true);
}

// main method
public static void main(String args[]) {

// creating instance of Frame class


AWTExample1 f = new AWTExample1();

}
AWT Example by Association

// importing Java AWT class


import java.awt.*;

// class AWTExample2 directly creates instance of Frame class


class AWTExample2 {

// initializing using constructor


AWTExample2() {

// 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);

// adding components into frame


f.add(b);
f.add(l);
f.add(t);

// frame size 300 width and 300 height


f.setSize(400,300);

// setting the title of frame


f.setTitle("Employee info");

// no layout
f.setLayout(null);

// setting visibility of frame


f.setVisible(true);
}
public static void main(String args[]) {
AWTExample2 awt_obj = new AWTExample2(); }}
Event Handling in Applet

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);
}

public void mouseDragged(MouseEvent me){ myapplet.html


Graphics g=getGraphics(); <html>
g.setColor(Color.white); <body>
g.fillOval(me.getX(),me.getY(),5,5); <applet code="MouseDrag.class"
} width="300" height="300">
public void mouseMoved(MouseEvent me){} </applet>
</body>
} </html>
Parameter in Applet

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)

import java.applet.Applet; myapplet.html


import java.awt.Graphics; <html>
<body>
public class UseParam extends Applet <applet code="UseParam.class"
{ width="300" height="300">
public void paint(Graphics g){ <param name="msg" value="Welcome to
String str=getParameter("msg"); applet">
g.drawString(str,50, 50); </applet>
} </body>
} </html>
AWT TextField Example with ActionListener
import java.awt.*;
import java.awt.event.*;
// Our class extends Frame class and implements ActionListener interface
public class TextFieldExample2 extends Frame implements ActionListener
{
// creating instances of TextField and Button class
TextField tf1, tf2, tf3;
Button b1, b2;
// instantiating using constructor
TextFieldExample2() {
// instantiating objects of text field and button
// setting position of components in frame
tf1 = new TextField();
tf1.setBounds(50, 50, 150, 20);
tf2 = new TextField();
tf2.setBounds(50, 100, 150, 20);
tf3 = new TextField();
tf3.setBounds(50, 150, 150, 20);
tf3.setEditable(false);
b1 = new Button("+");
b1.setBounds(50, 200, 50, 50);
b2 = new Button("-");
b2.setBounds(120,200,50,50);
// adding action listener
b1.addActionListener(this);
b2.addActionListener(this);
// adding components to frame
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
// setting size, layout and visibility of frame
setSize(300,300);
setLayout(null);
setVisible(true);
}
// defining the actionPerformed method to generate an event on buttons
public void actionPerformed(ActionEvent e) {
String s1 = tf1.getText();
String s2 = tf2.getText();
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
int c = 0;
if (e.getSource() == b1){
c = a + b; }
else if (e.getSource() == b2){
c = a - b;
}
String result = String.valueOf(c);
tf3.setText(result);
}
// main method
public static void main(String[] args) {
new TextFieldExample2();
}
}
AWT Label Example with ActionListener
import java.awt.*;
import java.awt.event.*;

// creating class which implements ActionListener interface and inherits Frame


class
public class LabelExample2 extends Frame implements ActionListener{

// creating objects of TextField, Label and Button class


TextField tf;
Label l;
Button b;

// constructor to instantiate the above objects


LabelExample2() {
tf = new TextField();
tf.setBounds(50, 50, 150, 20);

l = new Label();
l.setBounds(50, 100, 250, 20);

b = new Button("Find IP");


b.setBounds(50,150,60,30);
b.addActionListener(this);
add(b);
add(tf);
add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}

// defining actionPerformed method to generate an event


public void actionPerformed(ActionEvent e) {
try {
String host = tf.getText();
String ip = java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}
catch (Exception ex) {
System.out.println(ex);
}
}

// 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);

// adding ActionListener to button


b.addActionListener(this);
// adding components to frame
add(l1);
add(l2);
add(area);
add(b);
setSize(400, 450);
setLayout(null);
setVisible(true);
}
// generating event text area to count number of words and characters
public void actionPerformed(ActionEvent e) {
String text = area.getText();
String words[]=text.split("\\s");
//splits the string based on whitespace
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
// main method
public static void main(String[] args) {
new TextAreaExample2(); }}
import java.awt.*; AWT Checkbox Example with ItemListener
import java.awt.event.*;
public class CheckboxExample2
{
// constructor to initialize
CheckboxExample2() {
// creating the frame
Frame f = new Frame ("CheckBox Example");
// creating the label
final Label label = new Label();
// setting the alignment, size of label
label.setAlignment(Label.CENTER);
label.setSize(400,100);
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100, 150, 50, 50);
// adding the checkbox to frame
f.add(checkbox1);
f.add(checkbox2);
f.add(label);
// adding event to the checkboxes
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new CheckboxExample2();
}
}
AWT CheckboxGroup Example with ItemListener
import java.awt.*;
import java.awt.event.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, false);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
checkBox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ checkbox: Checked");
}
});
checkBox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java checkbox: Checked");
}
});
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
AWT Choice Example with ActionListener
import java.awt.*;
import java.awt.event.*;

public class ChoiceExample2 {

// class constructor
ChoiceExample2() {

// creating a frame
Frame f = new Frame();

// creating a final object of Label class


final Label label = new Label();

// setting alignment and size of label component


label.setAlignment(Label.CENTER);
label.setSize(400, 100);

// creating a button
Button b = new Button("Show");

// setting the bounds of button


b.setBounds(200, 100, 50, 20);
// creating final object of Choice class
final Choice c = new Choice();

// setting bounds of choice menu


c.setBounds(100, 100, 75, 75);

// adding 5 items to choice menu


c.add("C");
c.add("C++");
c.add("Java");
c.add("PHP");
c.add("Android");

// adding above components into the frame


f.add(c);
f.add(label);
f.add(b);

// setting size, layout and visibility of frame


f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
// adding event to the button
// which displays the selected item from the list when button is clicked
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "+
c.getItem(c.getSelectedIndex());
label.setText(data);
}
});
}

// 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");

// adding List, Label and Button to the frame


f.add(l1);
f.add(l2);
f.add(label);
f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);

// generating event on the button


b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected:
"+l1.getItem(l1.getSelectedIndex());
data += ", Framework Selected:";
for(String frame:l2.getSelectedItems()) {
data += frame + " ";
}
label.setText(data);
}
});
}

// 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.*;

// class to construct a frame and containing main method


public class CanvasExample
{
// class constructor
public CanvasExample()
{

// creating a frame
Frame f = new Frame("Canvas Example");
// adding canvas to frame
f.add(new MyCanvas());

// setting layout, size and visibility of frame


f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
}
public static void main(String args[])
{
new CanvasExample();
}
}

// class which inherits the Canvas class


// to create Canvas
class MyCanvas extends Canvas
{
// class constructor
public MyCanvas() {
setBackground (Color.GRAY);
setSize(300, 200);
}
// paint() method to draw inside the canvas
public void paint(Graphics g)
{

// 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.*;

public class ScrollbarExample2 {

// class constructor
ScrollbarExample2() {
// creating a Frame with a title
Frame f = new Frame("Scrollbar Example");

// creating a final object of Label


final Label label = new Label();

// setting alignment and size of label object


label.setAlignment(Label.CENTER);
label.setSize(400, 100);

// creating a final object of Scrollbar class


final Scrollbar s = new Scrollbar();
s.setBounds(100, 100, 50, 100);

// adding Scrollbar and Label to the Frame


f.add(s);
f.add(label);

// setting the size, layout, and visibility of frame


f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);

// adding AdjustmentListener to the scrollbar object


s.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
label.setText("Vertical Scrollbar value is:"+ s.getValue());
}
});
}

// 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.

Unlike AWT, 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 Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
No. Java AWT Java Swing

1) AWT components are platform- Java swing components


dependent. are platform-independent.

2) AWT components Swing components are lightweight.


are heavyweight.

3) AWT doesn't support pluggable Swing supports pluggable look and


look and feel. feel.

4) AWT provides less Swing provides more powerful


components than Swing. components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.
Method Description

public void add(Component c) add a component on another


component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager sets the layout manager for the
m) component.
public void setVisible(boolean b) sets the visibility of the component. It
is by default false.

Java Swing Examples

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 java.awt.*;
import javax.swing.JFrame; Graphics in Swing

public class DisplayGraphics extends Canvas{

public void paint(Graphics g) {


g.drawString("Hello",40,40);
setBackground(Color.WHITE);
g.fillRect(130, 30,100, 80);
g.drawOval(30,130,50, 60);
setForeground(Color.RED);
g.fillOval(130,130,50, 60);
g.drawArc(30, 200, 40,50,90,60);
g.fillArc(30, 130, 40,50,180,40);

}
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

JMenuBar, JMenu and JMenuItem

JPopupMenu
Example of BorderLayout class: Using
import java.awt.*; BorderLayout() constructor
import javax.swing.*;

public class Border


{
JFrame f;
Border()
{
f = new JFrame();

// 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.*;

public class GridLayoutExample


{
JFrame frameObj;

// 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);

// setting the grid layout using the parameterless constructor


frameObj.setLayout(new GridLayout());

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

// setting grid layout of 3 rows and 3 columns


f.setLayout(new GridLayout(3,3));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ColorChooserExample extends JFrame implements ActionListener{
JFrame f;
JButton b;
JTextArea ta;
ColorChooserExample(){
f=new JFrame("Color Chooser Example.");
b=new JButton("Pad Color");
b.setBounds(200,250,100,30);
ta=new JTextArea();
ta.setBounds(10,10,300,200);
b.addActionListener(this);
f.add(b);f.add(ta);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true); }
public void actionPerformed(ActionEvent e){
Color c=JColorChooser.showDialog(this,"Choose",Color.CYAN);
ta.setBackground(c);
}
public static void main(String[] args) {
new ColorChooserExample();
}}
static Color showDialog(Component c, String title, Color initialColor): It is used
to show the color chooser dialog box.
JTabbedPane
import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new TabbedPaneExample();
}}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static JDialog d;
DialogExample() {
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{ public void actionPerformed( ActionEvent e )
{ DialogExample.d.setVisible(false); } });
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
import java.awt.*;
JPanel
import javax.swing.*;
public class PanelExample {
PanelExample()
{
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}}
JFileChooser

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.

public abstract void mouseClicked(MouseEvent e);


public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
public abstract void mouseReleased(MouseEvent e);

MouseListener Example

MouseListenerExample2
MouseMotionListener Interface

MouseMotionListener is notified whenever you move or drag mouse. It is notified


against MouseEvent. The MouseMotionListener interface is found in java.awt.event
package. It has two methods.

public abstract void mouseDragged(MouseEvent e);


public abstract void mouseMoved(MouseEvent e);

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.

public abstract void keyPressed (KeyEvent e);


public abstract void keyReleased (KeyEvent e);
public abstract void keyTyped (KeyEvent e);

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.

Sr. no. Method signature Description


1. public abstract void windowActivated (WindowEvent e); It is called when the Window is set to
be an active Window.
2. public abstract void windowClosed (WindowEvent e); It is called when a window has been
closed as the result of calling dispose
on the window.
3. public abstract void windowClosing (WindowEvent e); It is called when the user attempts to
close the window from the system
menu of the window.
4. public abstract void windowDeactivated (WindowEvent e); It is called when a Window is not an
active Window anymore.
5. public abstract void windowDeiconified (WindowEvent e); It is called when a window is
changed from a minimized to a
normal state.
6. public abstract void windowIconified (WindowEvent e); It is called when a window is
changed from a normal to a
minimized state.
7. public abstract void windowOpened (WindowEvent e); It is called when window is made
visible for the first time.
WindowExample
Adapter Classes
Java adapter classes provide the default implementation of listener interfaces
. If you inherit the adapter class, you will not be forced to provide the implementation
of all the methods of listener interfaces. So it saves code.

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.

The WindowAdapter class implements WindowListener interfaces. It provides the


default implementation of all the 7 methods of WindowListener interface. To override
the windowClosing() method, you can either use WindowAdapter class or
WindowListener interface.

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

JTabbedPane class is used to switch between a group of components by clicking


on a tab with a given title or icon. It inherits JComponent class.

TabbedPaneExample

JSlider
Puzzle Game

Puzzle Game
BallWorld game

Online Exam

PinBall game

TicTacToe game

Calculator

You might also like