0% found this document useful (0 votes)
8 views43 pages

Java Unit-V

Uploaded by

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

Java Unit-V

Uploaded by

dprabhavathi4919
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Introduction of AWT:-

 AWT stands for Abstract window Toolkit.


 It contains a number of predefined classes and methods that allows to create and manage GUI
(Graphical User Interface) applications.
 The java.awt package provides classes for AWT based programs such as TextField, Label,
TextArea, RadioButton, CheckBox etc..

Limitations of AWT:-
 AWT Components are Platform-dependent. Every component on the screen is displayed based
on the OS.
 AWT Components are heavy Weight. So, it will take more memory.
 It doesn’t supports for pluggable look and feel.
 It contains less components than Swing.
MVC Architecture in Java:-
 MVC stands for Modern View Controller.
 This architecture plays a major role internet based application designing.
 This architecture is used to separate the code of internet application based on their necessity.
 Model:- It represents Data-Base (Back-End data). So it allows the programmer to design all
related source code of Data Base accessibility.
 View:- It represents Front-End (User Interaction). So it allows the programmer to design User
Interface source code.
 Controller:- It act as bridge between Front-End and Back-End which means it provides an
interaction between Model and View.
Diagram for MVC:-
AWT Components:-
1. Button:- The Button class is used to create a labeled button that result in some action when the
button is pushed.
Button Constructors:-
public Button():- Creates a button with no text on it.
public Button (String text):- Creates a button with a text on it.
Methods of Button class:-
public void setText(String text):- It sets a string message on it.
public void setText(String text):- It gets a string message of button.
Program:-
import java.awt.*;
public class ButtonDemo
{
public static void main(String[] args)
{
Frame f=new Frame("Button Example");
Button b=new Button("Click Here");
b.setBounds(50,100,80,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
O/P:-
2. TextField:- This inbuilt class allows the programmer to enter his text and edit. It inherits from
TextComponents class.
Syntax:- TextField obj=new TextField(“text”);
Program:-
import java.awt.*;
public class TextFieldDemo
{
public static void main(String[] args)
{
Frame f=new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Welcome to CMRTC");
t1.setBounds(50,100,200,30);
t2=new TextField("Java Lab");
t2.setBounds(50,150,200,30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
O/P:-
3. TextArea:- This inbuilt class allows the programmer to enter his text in multiple lines and edit. It
inherits from TextComponents class.
Syntax:- TextArea obj=new TextArea(“text”);
Program:-
import java.awt.*;
public class TextAreaDemo
{
public static void main(String[] args)
{
Frame f=new Frame("TextField Example");
TextArea t;
t=new TextArea("Welcome to CMRTC\nJava Lab");
t.setBounds(10,30,300,300);
f.add(t);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
O/P:-
4. CheckBox:- This inbuilt class allows a programmer to select multiple options.
Syntax:- CheckBox obj=new CheckBox(“Text”);
Program:-
import java.awt.*;
public class CheckboxDemo
{
public static void main(String[] args)
{
Frame f=new Frame("Checkbox Example");
Checkbox cb1=new Checkbox("C");
cb1.setBounds(100,100,50,50);
Checkbox cb2=new Checkbox("Java");
cb2.setBounds(100,150,50,50);
f.add(cb1);
f.add(cb2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
O/P:-
5. Radio Button:- It allows the programmer to select any one among multiple options. To achieve
this programmer should use ButtonGroup. It allows the programmer to make the buttons to one
group, if he/she selected one option another will automatically deactivate.
Program:-
import java.awt.*;
public class RadioButtonDemo
{
public static void main(String[] args)
{
Frame f=new Frame("RadioButton Example");
CheckboxGroup cg=new CheckboxGroup();
Checkbox cb1=new Checkbox("C",cg,false);
cb1.setBounds(100,100,50,50);
Checkbox cb2=new Checkbox("Java",cg,false);
cb2.setBounds(100,150,50,50);
f.add(cb1);
f.add(cb2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
O/P:-
6. Choice:- This inbuilt class is used to show pop-up menu of choices. It allows programmer to
select any one, it will be shown on the top of a menu. It inherits Components class.
Syntax:- Choice obj=new Choice();
Program:-
import java.awt.*;
class ChoiceDemo
{
public static void main(String[] args)
{
Frame f=new Frame("Choice Example");
Choice c=new Choice();
c.setBounds(100,100,75,75);
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
O/P:-
7. List:- It is same as Choice class but it display all the options with scroll bar.
Syntax:- List obj=new List();
Program:-
import java.awt.*;
class ListDemo
{
public static void main(String[] args)
{
Frame f=new Frame("Choice Example");
List l=new List();
l.setBounds(100,100,75,30);
l.add("Item 1");
l.add("Item 2");
l.add("Item 3");
l.add("Item 4");
l.add("Item 5");
f.add(l);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
O/P:-
8. Label:- It allows the programmer to create a label before text field.
Constructors of Label:-
public Label():- Creates a label with an empty text.
public Label(String text):- Creates a label with a specific text.
Program:-
import java.awt.*;
class LabelDemo
{
public static void main(String[] args)
{
Frame f=new Frame("Label Example");
Label l1,l2;
l1=new Label("First Label:");
l1.setBounds(50,100,100,30);
l2=new Label("Second Label:");
l2.setBounds(50,150,100,30);
f.add(l1);
f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
O/P:-
9. Scrollbar:- It allows the programmer to design horizontal and vertical scrollbar to the window.
Syntax:- Scrollbar obj=new Scrollbar();
Program:-
import java.awt.*;
class ScrollbarDemo
{
public static void main(String[] args)
{
Frame f=new Frame("Scrollbar Example");
Scrollbar s=new Scrollbar();
s.setBounds(100,100,50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
O/P:-

10. MenuItem and Menu:- It allows the programmer to create drop-down list called menu. The
programmer can select any one among multiple. It allows the programmer to create sub menus
also.
Program:-
import java.awt.*;
class MenuDemo
{
public static void main(String[] args)
{
Frame f=new Frame("Menu Example");
MenuBar mb=new MenuBar();
Menu m=new Menu("Menu");
Menu sm=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");
m.add(i1);
m.add(i2);
m.add(i3);
sm.add(i4);
sm.add(i5);
m.add(sm);
mb.add(m);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
O/P:-
Containers in Java:- A container is a component that can hold other components. It provides a way to
organize and layout other components on the screen. The most common container class of awt are
Panel, Window, Frame and Dialog.
1. Panel:- A Panel is fundamental container component used for organizing and grouping other
GUI elements. It serves as a light-weight container that can hold and manage various AWT
components like buttons, labels, text fiels etc..
Syntax:- Panel obj=new Panel();
Program:-
import java.awt.*;
class PanelDemo extends Frame
{
PanelDemo()
{
setTitle("Panel Example");
setSize(400,300);
setLayout(new FlowLayout());
Panel p=new Panel();
p.setBackground(Color.LIGHT_GRAY);
Button b1=new Button("Button 1");
Button b2=new Button("Button 2");
p.add(b1);
p.add(b2);
add(p);
setVisible(true);
}
public static void main(String[] args)
{
new PanelDemo();
}
}
O/P:-
2. Window:- In java’s Abstract Window Toolkit(AWT), the Window class represents a top-level
window without borders or a menubar. It serves as a fundamental building block for creating
GUI (Graphical User Interfaces).
3. Frame:- In java’s Abstract Window Toolkit(AWT), a Frame is a top-level window that serves as a
main container for other GUI components. It provides a standard window structure, including a
title bar, borders and standard window controls like minimize, maximize and close buttons.
Program:-
import java.awt.*;
class FrameDemo
{
public static void main(String[] args)
{
Frame f=new Frame("Frame Example");
f.setSize(400,300);
f.setVisible(true);
}
}
O/P:-

4. Dialog:- In java’s Abstract Window Toolkit(AWT), a Dialog is a top-level window primarily used
to prompt the user for input or to display information that requires user attention. It differs
from a Frame in that it typically lacks minimize and maximize buttons, usually only having a close
button.
Syntax:- Dialog obj=new Dialog();
AWT Layout:-
 The layout Managers are used to arrange components in a particular manner on the container.
 If we do not use layout manager then also the components are positioned by the default layout
manager.
There are Five layouts available in the java awt library are: 1. BorderLayout 2. FlowLayout
3.GridLayout 4. CardLayout 5. GridBagLayout
1. BorderLayout:- The Border Layout is a layout which organizes components in terms of direction.
A border layout divides the frame or panel into five sections or regions: north, south, east, west
and center. Each region(area) may contain one component only. It is the default layout of frame
or window.
The BorderLayout provides five constants for each reason:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Program:-
import java.awt.*;
class BorderDemo
{
public static void main(String[] args)
{
Frame f=new Frame();
Button b1=new Button("NORTH");
Button b2=new Button("SOUTH");
Button b3=new Button("EAST");
Button b4=new Button("WEST");
Button b5=new Button("CENTER");
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
}
O/P:-

2. FlowLayout:- It is used to arrange the components in a line, one after another (in a flow).
Syntax:- FlowLayout obj=new FlowLayout();
Program:-
import java.awt.*;
class FlowDemo
{
public static void main(String[] args)
{
Frame f=new Frame();
Button b1=new Button("1");
Button b2=new Button("2");
Button b3=new Button("3");
Button b4=new Button("4");
Button b5=new Button("5");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
f.setSize(300,300);
f.setVisible(true);
}
}
O/P:-

3. GridLayout:- The GridLayout is used to arrange the components in rectangular grid. Each
component get added to a particular cell.
Syntax:- GridLayout obj=new GridLayout(int rows, int columns);
Program:-
import java.awt.*;
class GridDemo
{
public static void main(String[] args)
{
Frame f=new Frame();
Button b1=new Button("1");
Button b2=new Button("2");
Button b3=new Button("3");
Button b4=new Button("4");
Button b5=new Button("5");
Button b6=new Button("6");
Button b7=new Button("7");
Button b8=new Button("8");
Button b9=new Button("9");
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);
f.setLayout(new GridLayout(3,3));
f.setSize(300,300);
f.setVisible(true);
}
}
O/P:-

4. CardLayout:- The CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known as
CardLayout.
Syntax:- CardLayout obj=new CardLayout();
Program:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class CardDemo extends JFrame implements ActionListener
{
CardLayout card;
Button b1,b2,b3;
Container c;
CardDemo()
{
c=getContentPane();//just like a window
card=new CardLayout(40,30);//40 hor space and 30 ver space
c.setLayout(card);
b1=new Button("Apple");
b2=new Button("Bat");
b3=new Button("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add(b1);
c.add(b2);
c.add(b3);
}
public void actionPerformed(ActionEvent ae)
{
card.next(c);
}
public static void main(String[] args)
{
CardDemo cd=new CardDemo();
cd.setSize(400,400);
cd.setVisible(true);
cd.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
O/P:-
5. GridBagLayout:- It is very flexible layout which provides an organized way to arrange
components. Constraints of GridBagLayout are gridx(), gridy(), gridheight() and gridwidth()
which is used to place the component in particular position.
Program:-
import java.awt.*;
class GridBagDemo extends Frame
{
GridBagDemo()
{
GridBagLayout gbl=new GridBagLayout();
setLayout(gbl);
GridBagConstraints gbc=new GridBagConstraints();
Button b1=new Button("Button1");
Button b2=new Button("Button2");
Button b3=new Button("Button3");
Button b4=new Button("Button4");
Button b5=new Button("Button5");
gbc.gridx=0;
gbc.gridy=0;
add(b1,gbc);
gbc.gridx=1;
gbc.gridy=0;
add(b2,gbc);
gbc.gridx=0;
gbc.gridy=1;
add(b3,gbc);
gbc.gridx=1;
gbc.gridy=1;
add(b4,gbc);
gbc.gridx=0;
gbc.gridy=2;
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.gridwidth=2;
gbc.gridheight=1;
add(b5,gbc);
setSize(300,300);
setVisible(true);
}
public static void main(String[] args)
{
new GridBagDemo();
}
}
O/P:-

Event Handling
Event:- In Object Oriented Programming Language Event is an object which changes the state of source.
Ex:-
1) Click on ok button.
2) Select Menu Item
3) Close Window
Here click, select, close are events. Button, menu item, window are sources.
Mostly Events are related to user interaction, but in some generates automatically for example:
timer expire, system file corrupted etc.
Event Delegation Model:- In this method, the programmer should register the event before invoking.
Java contains many predefined methods for event registration.
Syntax:- source_object.addtypeListener(this)
Ex:-
1) b1.addActionListener(this) (b1->button object)
2) b1.addMouseListener(this) (for mouse event)
3) b1.addKeyListener(this) (for keyboard event)
The programmer can also unregister the event.
Syntax:- source_object.remove typeListener(this)
Ex:- b1.removeActionListener(this) (b1->button object)
Event Classes:- Java contains so many predefined classes and interfaces for Event Handling. They are
defined in awt(abstract window toolkit) package. awt contains so many predefined classes for creating
GUI (Graphical User Interface) components. For example:- button, check box etc.
Event classes list given below:-
1) ActionEvent
2) AdjustmentEvent
3) ComponentEvent
4) Container Event
5) ItemEvent
6) FocusEvent -> InputEvent
7) TextEvent
8) KeyEvent
9) MouseEvent
10) WindowEvent
EventListener Interfaces:- Java does not allow to extends application from classes (multiple-inheritence
is not possible through class). Event listener interfaces supports for multiple inheritance and they
supports for abstraction.
Event Interfaces list given below:-
1) ActionListener
2) Adjustment Listener
3) Component Listener
4) Container Listener
5) ItemListener
6) Focus Listener
7) Text Listener
8) Key Listener
9) Mouse Listener
10) MouseMotion Listener
11) Window Listener

1) ActionListener :- It is used for click event. It contains only one abstract method
Public void actionPerformed(ActionEvent ae);
2) AdjustmentListener:- It is used for scroll event. It contains only one abstract method
Public void adjustmentValueChanged(AdjustmentEvent ae);
3) ComponentListener:- It contains 4 abstract methods:
Public void componentShown(ComponentEvent ce);
Public void componentHidden(ComponentEvent ce);
Public void componentMoved(ComponentEvent ce);
Public void componentResized(ComponentEvent ce);
4) ContainerListener:- It contains 2 abstract methods:
Public void ComponentAdded(ContainerEvent ce);
Public void ComponentRemoved(ContainerEvent ce);
5) ItemListener:- It is used for selection Event. It contains only one abstract method
Public void itemStateChanged(ItemEvent ie);
6) FocusListener :- It contains 2 abstract method
Public void focusGained(FocusEvent fe);
Public void focusLost(FocusEvent fe);
7) TextListener:- It is used for TextEvents. It contains only one abstract method
Public void valueChaged(TextEvent te);
8) KeyListener:- It is used for keyboard events. It contains 3 abstract methods.
Public void keyTyped(KeyEvent ke);
Public void keyPressed(KeyEvent ke);
Public void keyReleased(KeyEvent ke);
9) MouseListener:- Used for mouse event. It contains 5 abstract methods:
Public void mouseClicked(MouseEvent me);
Public void mousePressed(MouseEvent me);
Public void mouseEntered(MouseEvent me);
Public void mouseExited(MouseEvent me);
Public void mouseReleased(MouseEvent me);
10) MouseMotionListener:- It is also designed for mouse event. It contains 2 abstract methods:
Public void mouseMoved(MouseEvent me);
Public void mouseDragged(MouseEvent me);
11) WindowListener:- It contains 7 abstact methods:
Public void windowActivated(WindowEvent we);
Public void windowActivated(WindowEvent we);
Public void windowDectivated(WindowEvent we);
Public void windowIconified(WindowEvent we);
Public void windowDeiconified(WindowEvent we);
Public void windowClosed(WindowEvent we);
Public void windowClosing(WindowEvent we);
Public void windowOpened(WindowEvent we);
FlowLayout:- It is used to set the components horizontally from left to right.
add():- It is used to display on container.
JButton:- It is a component in Java Swing used to create a clickable button in a GUI. When a JButton is
clicked, it can trigger an action defined by an ActionListener.
Syntax:- JButton obj=new JButton();
Program for MouseEvent(JButton):-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JButtonDemo extends JFrame implements ActionListener
{
JLabel l1,l2;
JTextField t1,t2;
JButton b;
JButtonDemo()
{
FlowLayout fl=new FlowLayout();
setLayout(fl);
l1=new JLabel("Enter Value:");
add(l1);
t1=new JTextField(12);
add(t1);
b=new JButton("COMPUTE");
b.addActionListener(this);
add(b);
l2=new JLabel("Result:");
add(l2);
t2=new JTextField(12);
add(t2);
setVisible(true);
setSize(800,600);
}
public void actionPerformed(ActionEvent ae)
{
int n=Integer.parseInt(t1.getText());
int f=1;
while(n>=1)
{
f=f*n;
n--;
}
t2.setText(f+"");
}
public static void main(String[] args)
{
new JButtonDemo();
}
}
O/P:-
JToggleButton:- It is just like JButton class but it shows difference between pressed and unpressed on
button.
Syntax:- JToggleButton obj=new JToggleButton();
Program:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JTButtonDemo extends JFrame implements ActionListener
{
JToggleButton b;
JTextField t1,t2;
JLabel l1,l2;
JTButtonDemo()
{
FlowLayout fl=new FlowLayout();
setLayout(fl);
l1=new JLabel("Enter a value:");
add(l1);
t1=new JTextField(12);
add(t1);
b=new JToggleButton("Compute");
add(b);
b.addActionListener(this);
l2=new JLabel("Result:");
add(l2);
t2=new JTextField(12);
add(t2);
setVisible(true);
setSize(800,600);
setTitle("CMRTC");
}
public void actionPerformed(ActionEvent ae)
{
int n=Integer.parseInt(t1.getText());
int f=1;
while(n>=1)
{
f=f*n;
n--;
}
t2.setText(f+"");
}
public static void main(String[] args)
{
new JTButtonDemo();
}
}
O/P:-

JCheckBox:- It is a component in Java Swing used to create a checkbox, which allows users to select or
deselect an item. It is visually represents a box that can be toggled between a “checked” (selected) and
“unchecked” (deselected) state.
Syntax:- JCheckBox obj=new JCheckBox();
Program for JCheckBox:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JCBDemo extends JFrame implements ItemListener
{
JCheckBox c1,c2;
JTextField t;
JCBDemo()
{
FlowLayout fl=new FlowLayout();
setLayout(fl);
c1=new JCheckBox("Bold");
add(c1);
c1.addItemListener(this);
c2=new JCheckBox("Italic");
add(c2);
c2.addItemListener(this);
t=new JTextField("RamInfoTech",20);
add(t);
setVisible(true);
setSize(800,600);
}
public void itemStateChanged(ItemEvent ie)
{
if(c1.isSelected() && c2.isSelected())
t.setFont(new Font("Arial",Font.BOLD+Font.ITALIC,16));
else if(c1.isSelected() && !c2.isSelected())
t.setFont(new Font("Arial",Font.BOLD+Font.PLAIN,16));
else if(!c1.isSelected() && c2.isSelected())
t.setFont(new Font("Arial",Font.PLAIN+Font.ITALIC,16));
else
t.setFont(new Font("Arial",Font.PLAIN,16));
}
public static void main(String[] args)
{
new JCBDemo();
}
}
O/P:-
JRadioButton:- It is just like JCheckBox but it allows the user to select any one among multiple. It can
attained by ButtonGroup.
ButtonGroup:- It is a predefined class. It is used make two or more item into a group.
Ex:- if 2 radio buttons made a buttongroup. If one radio button is selected another radio button wiil
deactivate. So it is used any one option among multiple.
Program for JRadiobutton:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JRBDemo extends JFrame implements ActionListener
{
JRadioButton r1,r2;
JRBDemo()
{
FlowLayout fl=new FlowLayout();
setLayout(fl);
r1=new JRadioButton("Male");
add(r1);
r1.addActionListener(this);
r2=new JRadioButton("Female");
add(r2);
r2.addActionListener(this);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
setVisible(true);
setSize(800,600);
}
public void actionPerformed(ActionEvent ae)
{
if(r1.isSelected())
JOptionPane.showMessageDialog(null,"You selected Male");
if(r2.isSelected())
JOptionPane.showMessageDialog(null,"You selected Female");
}
public static void main(String[] args)
{
new JRBDemo();
}
}
O/P:-

JComboBox:- It is a Java Swing GUI component that provides a drop-down list of items from which the
user can select one.
Syntax:- JComboBox obj=new JComboBox();
Program for JComboBox:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JComboDemo extends JFrame implements ItemListener
{
JLabel l;
JComboBox c;
JComboDemo()
{
FlowLayout fl=new FlowLayout();
setLayout(fl);
c=new JComboBox();
c.addItem("Home");
c.addItem("Bird");
c.addItem("Computer");
add(c);
c.addItemListener(this);
l=new JLabel(new ImageIcon());
add(l);
setVisible(true);
setSize(800,600);
}
public void itemStateChanged(ItemEvent ie)
{
String s=(String)ie.getItem();
l.setIcon(new ImageIcon(s+".jpg"));
}
public static void main(String[] args)
{
new JComboDemo();
}
}

JPanel:- It is a light weight container component in java swing used to group and organize other GUI
components within a larger container just like JFrame.
JScrollPane:- It is a Swing component in java that provides a scrollbar view of another component. It is
used when the content of a component exceeds the visible of its container, allowing the user to scroll to
view the entire content.
Program for Jpanel and JScrollPane:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JSPDemo extends JFrame
{
JPanel jp;
JScrollPane jsp;
JSPDemo()
{
BorderLayout bl=new BorderLayout();
setLayout(bl);
jp=new JPanel();
jp.setLayout(new GridLayout(10,5));
for(int i=1;i<=50;i++)
jp.add(new JButton(i+""));
int v=JScrollPane.VERTICAL_SCROLLBAR_ALWAYS;
int h=JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS;
jsp=new JScrollPane(jp,v,h);
add(jsp);
setVisible(true);
setSize(800,600);
}
public static void main(String[] args)
{
new JSPDemo();
}
}
O/P:-

JTabbedPane:- It is a component within the java Swing library. It act as a container allowing multiple
JPanel to share same visual space within a window.
Program:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Pack extends JPanel
{
Pack()
{
add(new JRadioButton("MSOffice"));
add(new JRadioButton("Tally"));
add(new JRadioButton("DTP"));
}
}
class Lang extends JPanel
{
Lang()
{
add(new JButton("C"));
add(new JButton("Java"));
add(new JButton("Python"));
}
}
class JTabDemo extends JFrame
{
JTabbedPane jt;
JTabDemo()
{
jt=new JTabbedPane();
jt.addTab("Package",new Pack());
jt.addTab("Language",new Lang());
add(jt);
setVisible(true);
setSize(600,800);
}
public static void main(String[] args)
{
new JTabDemo();
}
}
O/P:-
Menus in Java:- In java, menus are used in GUI to provide users with a structured way to access various
commands and options within an application. They are typically found in menu bars at the top of the
window.
Program for Menu Designing:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JMBDemo extends JFrame implements ActionListener
{
JMBDemo()
{
MenuBar mb=new MenuBar();
setMenuBar(mb);
Menu f=new Menu("File");
f.add(new MenuItem("New"));
f.add(new MenuItem("Open"));
f.add(new MenuItem("Save"));
MenuShortcut mc=new MenuShortcut(KeyEvent.VK_C);
MenuItem c=new MenuItem("Close",mc);
f.addSeparator();
f.add(c);
c.addActionListener(this);
Menu e=new Menu("Edit");
e.add(new MenuItem("Cut"));
e.add(new MenuItem("Copy"));
e.add(new MenuItem("Paste"));
mb.add(f);
mb.add(e);
setVisible(true);
setSize(800,600);
}
public void actionPerformed(ActionEvent ae)
{
System.exit(1);
}
public static void main(String[] args)
{
new JMBDemo();
}
}
O/P:-
JList:- It is a component in Java Swing that display a list of objects and allows the user to select one or
more items items from that list. It is commonly used in GUI applications to present choices to the user.
Syntax:- JList obj=new JList();
Program:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JListDemo extends JFrame
{
JListDemo()
{
String week[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
JList l=new JList(week);
l.setBounds(50,30,80,150);
add(l);
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args)
{
new JListDemo();
}
}
O/P:-

Mouse Events in java:- They are handled using interface and classes within the “java.awt.event”
package, primarily “MouseListener” and “MouseMotionListener”.
Program:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseListenerExample extends JFrame implements MouseListener
{
JLabel l;
MouseListenerExample()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMouseListener(this);
l=new JLabel();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setTitle("CMRTC");
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
l.setText("Mouse Released");
}
public static void main(String[] args)
{
new MouseListenerExample();
}
}
O/P:-
Keyboard events in java:- Keyboard events in java are handled using the KeyListener interface, which is
part of the “java.awt.event” package.
Program:-
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyListenerExample extends JFrame implements KeyListener
{
JLabel l;
KeyListenerExample()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
l=new JLabel();
l.setBounds(20,50,200,100);
add(l);
setSize(300,300);
setLayout(null);
setTitle("CMRTC");
setVisible(true);
}
public void keyPressed(KeyEvent e)
{
l.setText("Keyboard Pressed");
}
public void keyReleased(KeyEvent e)
{
l.setText("Keyboard Released");
}
public void keyTyped(KeyEvent e)
{
l.setText("Keyboard Typed");
}
public static void main(String[] args)
{
new KeyListenerExample();
}
}
O/P:-

Adapter Classes in Java:- Adapter classes in java are abstract classes that provides empty, default
implementation for all methods of a corresponding listener interface. Their primary purpose is to
simplify event handling, particularly in GUI.
When implementing a listener interface that contains multiple methods (ex: MouseListener with
mousePressed(), mouseReleased() etc), you are required to provide an implementation for every
method, even if you only need to handle one or more specific methods. To overcome this problem they
introduced Adapter classes concept to eliminate this burden.
Interfaces Adapter Classes
WindowListener WindowAdapter
MouseListener MouseAdapter
MouseMoitionListener MouseMoitionAdapter
KeyListener KeyAdapter
FocusListener FocusAdapter
ComponentListener ComponentAdapter
Program:-
import java.awt.*;
import java.awt.event.*;
class MouseAdapterExample extends MouseAdapter
{
public static void main(String[] args)
{
public void mouseClicked(MouseEvent me)
{
System.out.println("Mouse clicked");
}
}
}

Applet
 Applet is a small java program used to develop internet application.
 Applet is a special type of program that is embedded in the webpage to generate the dynamic
content
 It does not a stand alone application so it does not contain main() method.
 Whenever we want to design applet program the programmer should design 2 types of
programs. 1)Applet program 2) HTML Program
 Applet program must be run under an applet viewer.
 Applet= HTML + java class code.
 A HTML page with contains .class file is called applet.
Program:-
import java.applet.Applet;
import java.awt.*;
public class Robo
{
public void paint(Graphics g)
{
g.drawString("Welcome to Applet program",10,10);
}
}
Compile:- javac Robo.java
HTML program:-
<applet code="Robo.class" width=200 height=200>
</applet>
Run:- appletviewer Robo.html
Applet Life Cycle:- It contains four stages. They are:-
1) Born or initialization state:- This state is used to load an applet into the memory. It is invoked by
using init().In this state the programmer can initialize the variable or load images or color set-up.
It is executed only once.
Syntax:-
public void init()
{
-----
-----
}
2) Running or start state:- It is used to run an applet. It is invoked by using start(). Ex:-Connecting
to the database, opening a file or processing, etc.
Public void start()
{
-----
-----
}
It is executed immediately after completion of init()
3) Idle or stop state:- It is used to end applet execution. It is invoked by stop(). Ex:- Disconnecting
from database, closing a file or processing has finished etc
Public void stop()
{
-----
-----
}
Start and stop state can be executed multiple times
4) Dead or destroy state:- It is used to terminate the applet. It removes the memory. It is invoked
by using destroy().
Public void destroy()
{
-----
-----
}
Diagram:-
Applets and Applications in Java:-
1. Execution of Applet does not starts from main() 1. Execution of java application starts from main()
and Applet does not contain main()
2. Applets can’t be run on their own. Applets have 2. Java applications run on their own.
to be Embedded inside a webpage to get executed
3. Applets are executed using appletviewer or 3. Applications are executed in command-prompt.
browser
4. Applets have their own Life-Cycle methods such 4. Applications have their own Life-Cycle execution
as init(), start(), paint(), stop() and destroy(). begins from main()

Passing Parameters to an Applet or Passing Input to an Applet:-


import java.applet.*;
import java.awt.*;//awt contain Component class which contain paint()
/*<applet code=ParameterApplet width=500 height=500>
<param name=xvalue value="Ramesh">
<param name=yvalue value="Mahesh">
</applet>*/
public class ParameterApplet extends Applet
{
String x,y;
public void init()
{
x=getParameter("xvalue");
y=getParameter("yvalue");
}
public void paint(Graphics g)
{
g.drawString("Hai "+x,10,40);
g.drawString("Hai "+y,10,70);
}
}

Creating swing Applet in java:- JApplet is a class in the Swing library of the java programming language
that represents a lightweight, embedded applet that runs within a web page. It is the subclass of Applet
class in “swing” package. It contains the features of Applet class and extra features related to swing
package.
Program:-
import javax.swing.*;
/*<applet code="SwingAppletDemo" width="200" height="100">
</applet>*/
class SwingAppletDemo extends JApplet
{
public void init()
{
JButton b=new JButton("Click me");
add(b);
}
}

Compile: javac SwingAppletDemo.java


Execute: appletviewer SwingAppletDemo.java
Painting in Swing:- It allows the programmer to paint (draw) something on the Frame by using “paint()”.
It belongs to Component class and its signature is “public void paint(Graphics g)”. Graphics class belongs
to “java.awt” package.
Program:-
import java.awt.*;
class PaintDemo extends Frame
{
public void paint(Graphics g)
{
g.drawString("Hello",100,60);
g.drawRect(40,40,50,20);
}
public static void main(String[] args)
{
PaintDemo p=new PaintDemo();
p.setVisible(true);
p.setSize(300,200);
}
}
O/P:-

Nested Classes
Java allows the programmer to design a class within a class is called nested classes. First class is
called outer class and second class is called inner class.
Benefits of nested classes:-
1) All related classes designed under a single unit. So it increases program understandability.
2) The inside class members is accessible from outside. It is not accessible from some where else.
So it shows data hiding ethnic.
3) Nested classes implementation leads to increase program understandability and decreases
programming size.
Basically nested classes are divided into 2 types:-
1) Non-Static nested class(Inner Class)
2) Static Nested Class
1) Inner class:- It is used to access non-static members only. It is divided into 3 types:
1) Member Inner Class
2) Local Inner Class
3) Anonymous Inner Class
1) Member Inner class:- A class which is designed inside a class and outside of all methods
member inner class. All outer class member can be accessible in inner class.
Program:-
class Outer
{
int x=10;
class Inner
{
void show()
{
System.out.println("Inner class show method");
System.out.println("Outer class x="+x);
}
}
void display()
{
new Inner().show();
}
public static void main(String[] args)
{
new Outer().display();
}
}
O/P:-
Inner class show method
Outer class x=10
2) Local Inner class:- The class which is designed inside a method is called local inner class. All inner
class members are accessible inside a method only.
class Outer
{
void display()
{
class Inner
{
void show()
{
System.out.println("Inner class show method");
}
}
new Inner().show();
}
public static void main(String[] args)
{
new Outer().display();
}
}
O/P:- Inner class show method
3) Anonymous Inner Class:- The inner class which does not have class name is called Anonymous
Inner Class. It is used in implementation of abstract class.
Program:-
abstract class A
{
abstract void show();
}
class B
{
public static void main(String[] args)
{
A x=new A(){
void show()
{
System.out.println("Anonymous inner class show()");
}
};
x.show();
}
}
O/P:- Anonymous inner class show()
2)Static Nested Classes:- It is used to access static members. The programmer should specify outer class
name and inner class name to access the properties.
Program:-
class Outer
{
static int x=10;
static class Inner
{
static void show()
{
System.out.println("Static inner class show method");
System.out.println("Static x="+x);
}
}
public static void main(String[] args)
{
Outer.Inner.show();
}
}
O/P:-
Static inner class show method
Static x=10

You might also like