0% found this document useful (0 votes)
3 views102 pages

Java Module4

The document provides an overview of Java AWT, Swing, and networking, focusing on GUI development with applets and components. It outlines the lifecycle of applets, the structure of HTML pages, and the differences between AWT and Swing, highlighting the advantages of Swing's lightweight and platform-independent components. Additionally, it includes examples of creating buttons, labels, text fields, and frames using Java Swing.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
3 views102 pages

Java Module4

The document provides an overview of Java AWT, Swing, and networking, focusing on GUI development with applets and components. It outlines the lifecycle of applets, the structure of HTML pages, and the differences between AWT and Swing, highlighting the advantages of Swing's lightweight and platform-independent components. Additionally, it includes examples of creating buttons, labels, text fields, and frames using Java Swing.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 102

Module -4

AWT, SWING and NETWORKING


INTRODUCTIO
N
•Abstract Window Toolkit (AWT) is an API to develop GUI or window – based
applications in java.

•A graphical user interface is built of graphical elements called components. Typical


components include such items as buttons, scrollbars, and text fields.

•Java AWT Components are platform dependent that is components are displayed
according to the view of operating system.

•The Container class is a subclass of Component. Container class used to display non-
container class.

•In java GUI can be design using some predefined classes. All these classes are defined
in java.awt package.
APPLET

• Applet is a small program


– can be placed on a web page
– will be executed by the web browser
– give web pages “dynamic content”
– Applet class is one of the AWT components

• Java applets are usually graphical


– Draw graphics in a defined screen area
– Enable user interaction with GUI elements
ADVANTAGES AND DISADVANTAGES OF APPLET
Advantages
• 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.
Disadvantages
• Plugin is required at client browser to execute
applet.
STEPS IN DEVELOPMENT OF APPLET
1. Build an applet code (.java)
2. Create an executable applet (.class)
3. Desigining a web page using HTML tags
4. Prepare <APPLET> Tag
5. Incorporate <APPLET> Tag into web page
6. Create HTML file
7. Test the Applet
LIFECYCLE OF JAVA APPLET
• Applet is initialized.
• Applet is started.
• Applet is painted.
• Applet is stopped.
• Applet is destroyed.
Methods are called in this order
• init and destroy are only called
init() once each
• start and stop are called whenever the
start()
browser enters and leaves the page
• do some work is code called by your
do some work
listeners
stop() • paint is called when the applet needs
to be repainted
destroy()
LIFECYCLE METHODS FOR APPLET:
java.applet.Applet class
It provides 4 life cycle methods of applet.
• public void init(): is used to initialized 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.

java.awt.Component class
• 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.
STRUCTURE OF AN HTML PAGE

HTML • Most HTML


tags are
containers.
HEAD BODY • A container
is
<tag> to
TITLE (content)
</tag>
APPLETS AND WEB PAGES – HTML

• Create the web page <HTML>


code using a text
<HEAD>
editor
• Save it with an </HEAD>
.html suffix <BODY>
• Open this file with <APPLET CODE = . . . >
appletviewer or with </APPLET>
a web browser that
supports Java </BODY>
</HTML>
SYNTAX
import java.applet.Applet;
import java.awt.Graphics;
……
…….
public class Appletname
extends Applet
{
…..
……
public void
paint(Graphics g)
{ ….
SIMPLE EXAMPLE OF APPLET
•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">
</applet>
public void paint(Graphics g) </body>
</html>
{
g.drawString("welcome",150,150);
}

}
EXECUTING AND RUNNING AN APPLET
There are two ways to run an applet
• By html file.
• By appletViewer tool (for testing purpose).

Execute the applet by appletviewer tool, write


in command prompt:
• c:\>javac First.java
• c:\>appletviewer First.html
APPLICATIONS
• QuickTime movies
• Flash movies
• Windows Media Player
• 3D modeling
• Browser games
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.

Window
The window is the container that have no borders and menu bars. You must
use frame, dialog or another window for creating a window.

Panel
The Panel is the container that doesn't contain title bar and menu bars.
It can have other components like button, textfield, etc.

Frame
The Frame is the container that contain title bar and can have menu
bars. It can have other components like button, textfield, etc.
Useful Methods of Component class

Method Description

public void add(Component c) inserts a component in container

public void setSize(int width,int sets the size (width and height) of the
height) component.

public void defines the layout manager for the component.


setLayout(LayoutManager m)

public void setVisible(boolean changes the visibility of the component, by


status) default false.
Java Swing

Java Swing is a 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.
Difference between AWT and Swing

No. Java AWT Java Swing

1) Java swing components are platform-


AWT components are platform-
dependent. independent.

2) AWT components are heavyweight. Swing components are lightweight.

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

4) AWT provides less components than Swing provides more powerful components
Swing. such as tables, lists, scrollpanes,
colorchooser, etc.

5) AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data, view
represents presentation and controller acts as
an interface between model and view.
Java Swing Examples
There are two ways to create a frame:
o By extending Frame class (inheritance)
o By creating the object of Frame class (association)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it on the JFrame object inside
the main() method.
Simple example of Swing by inheritance

import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame

Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);

add(b);//adding button on frame


setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new Simple2();
}}
Simple example of Swing by creating the object of Frame class

FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("clickme");//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
}}
Overview of Swing Components
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits AbstractButton class.

Commonly used Constructors:

Constructor Description

JButton() It creates a button with


no text and icon.
JButton(String s) It creates a button with
the specified text.
JButton(Icon i) It creates a button with
the specified icon object.
Commonly used Methods of AbstractButton class:

Methods Description

void setText(String s) It is used to set specified text on


button
String getText() It is used to return the text of the
button.
void setEnabled(boolean b) It is used to enable or disable the
button.
void setIcon(Icon b) It is used to set the specified Icon
on the button.

Icon getIcon() It is used to get the Icon of the


button.
void setMnemonic(int a) It is used to set the mnemonic on
the button.
void It is used to add the action listener
addActionListener(ActionListener to this object.
a)
Java JButton Example
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Example of displaying image on the button:
import javax.swing.*;
public class ButtonExample{
ButtonExample(){
JFrame f=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon("D:\\icon.png"));
b.setBounds(100,100,100, 40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new ButtonExample();
}
}
Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a single line of read only text.
The text can be changed by an application but a user cannot edit it directly. It inherits JComponent class.
JLabel class declaration

Constructor Description

JLabel() Creates a JLabel instance with


no image and with an empty
string for the title.
JLabel(String s) Creates a JLabel instance with
Commonly used Constructors: the specified text.
JLabel(Icon i) Creates a JLabel instance with
the specified image.
JLabel(String s, Icon i, int Creates a JLabel instance with
horizontalAlignment) the specified text, image, and
horizontal alignment.
Commonly used Methods:

Methods Description

String getText() t returns the text string that a


label displays.
void setText(String text) It defines the single line of text
this component will display.

void setHorizontalAlignment(int It sets the alignment of the


alignment) label's contents along the X axis.

Icon getIcon() It returns the graphic image that


the label displays.

int getHorizontalAlignment() It returns the alignment of the


label's contents along the X axis.
Java JLabel Example
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Java JTextField
The object of a JTextField class is a text component that allows the editing of a single
line text. It inherits JTextComponent class.

Constructor Description

JTextField() Creates a new TextField


JTextField(String text) Creates a new TextField
ommonly used Constructors: initialized with the specified
text.
JTextField(String text, int Creates a new TextField
columns) initialized with the specified
text and columns.
JTextField(int columns) Creates a new empty
TextField with the specified
number of columns.
Commonly used Methods:

Methods Description

void addActionListener(ActionListener l) It is used to add the specified action listener


to receive action events from this textfield.

Action getAction() It returns the currently set Action for this


ActionEvent source, or null if no Action is
set.

void setFont(Font f) It is used to set the current font.

void removeActionListener(ActionListener l) It is used to remove the specified action


listener so that it no longer receives action
events from this textfield.
Java JTextField Example

import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Java.");
t1.setBounds(50,100, 200,30);
t2=new JTextField(“welcome");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Containers
Java Jframe:The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
JFrame works like the main window where components like labels, buttons, textfields are added to create a
GUI.

Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation() method.
JFrame Example
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Jpanel;
public class JFrameExample {
public static void main(String s[]) {
JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("JFrame By Example");
JButton button = new JButton();
button.setText("Button");
panel.add(label);
panel.add(button);
frame.add(panel);
frame.setSize(200, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}}
JDialog
The JDialog control represents a top level window with a border and a title used to
take some form of input from the user. It inherits the Dialog class.
Unlike JFrame, it doesn't have maximize and minimize buttons.

Commonly used Constructors


Constructor Description

JDialog() It is used to create a modeless dialog without a title and


without a specified Frame owner.

JDialog(Frame owner) It is used to create a modeless dialog with specified


Frame as its owner and an empty title.

JDialog(Frame owner, String title, It is used to create a dialog with the specified title,
boolean modal) owner Frame and modality.

• A modal dialog blocks input to all other windows in the application until the dialog is closed.
Java JDialog Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
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)
{
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();} }
Java JPanel Example
JPanel import java.awt.*;
import javax.swing.*;
The JPanel is a simplest container class. It public class PanelExample
{ PanelExample()
provides space in which an application can {
attach any other component. It inherits the JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
JComponents class.
panel.setBounds(40,80,200,200);
It doesn't have title bar.
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();
Check boxes
• The JCheckBox class, which provides the functionality of a check box, is a concrete implementation of
AbstractButton.
• Some of its constructors are shown here:
JCheckBox(Icon i)
JCheckBox(Icon i, boolean state)
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean state)
• Here, i is the icon for the button. The text is specified by s. If state is true, the check box is initially selected.
Otherwise, it is not.
• The state of the check box can be changed via the following method:
void setSelected(boolean state)
• Here, state is true if the check box should be checked.
import javax.swing.*;
import java.awt.*;
checkBox2.addActionListener(new ActionListener() {
import java.awt.event.*;
public void actionPerformed(ActionEvent e) {
public class CheckboxExample {
String message = "Selected: ";
public static void main(String[] args) {
if (checkBox1.isSelected()) {
// Create a new JFrame
message += "Option 1 ";
JFrame frame = new JFrame("Checkbox Example");
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
if (checkBox2.isSelected()) {
frame.setSize(300, 200);
message += "Option 2";
frame.setLayout(new FlowLayout()); // Set layout for
}
the frame
label.setText(message);
// Create a JLabel to display messages
}
JLabel label = new JLabel("No option selected");
});
// Create checkboxes
// Add components to the frame
JCheckBox checkBox1 = new JCheckBox("Option 1");
frame.add(checkBox1);
JCheckBox checkBox2 = new JCheckBox("Option 2");
frame.add(checkBox2);
// Add action listeners to checkboxes
frame.add(label);
checkBox1.addActionListener(new ActionListener() {
// Make the frame visible
public void actionPerformed(ActionEvent e) {
frame.setVisible(true);
String message = "Selected: ";
}
if (checkBox1.isSelected()) {
}
message += "Option 1 ";
}
if (checkBox2.isSelected()) {
message += "Option 2";
}
label.setText(message);
}
});
Scroll Panes
• Scrollbar generates adjustment events when the scroll bar is manipulated.
• Scrollbar creates a scroll bar control.
• Scroll bars are used to select continuous values between a specified minimum
and maximum.
• Scroll bars may be oriented horizontally or vertically.
• A scroll bar is actually a composite of several individual parts.
• Each end has an arrow that you can click to move the current value of the scroll
bar one unit in the direction of the arrow.
• The current value of the scroll bar relative to its minimum and maximum values
is indicated by the slider box (or thumb) for the scroll bar.
• The slider box can be dragged by the user to a new position. The scroll bar will
then reflect this value.
• Scrollbar defines the following constructors:
Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
• The first form creates a vertical scroll bar.
• The second and third forms allow you to specify the orientation of the
scroll bar. If style is Scrollbar.VERTICAL, a vertical scroll bar is created. If
style is Scrollbar.HORIZONTAL, the scroll bar is horizontal.
• In the third form of the constructor, the initial value of the scroll bar is
passed in initialValue.
• The number of units represented by the height of the thumb is passed in
thumbSize.
• The minimum and maximum values for the scroll bar are specified by min
and max.
Example: Scroll panes
import javax.swing.*;
import java.awt.*;
Import java.awt.event.*;
public class ScrollbarExample {
public static void main(String[] args) {
// Create a new JFrame
JFrame frame = new JFrame("ScrollBar Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLayout(new BorderLayout());
// Create a JScrollBar
JScrollBar verticalScrollBar = new
JScrollBar(JScrollBar.VERTICAL, 0, 0, 0, 50);
// Create a JLabel to display scrollbar value
JLabel label = new JLabel("Scroll Value: 0");
label.setHorizontalAlignment(JLabel.CENTER);
// Add an adjustment listener to the scrollbar
verticalScrollBar.addAdjustmentListener(new
AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
int value = verticalScrollBar.getValue();
label.setText("Scroll Value: " + value);
}
});
// Add components to the frame
frame.add(label, BorderLayout.CENTER);
frame.add(verticalScrollBar, BorderLayout.EAST);
// Make the frame visible
frame.setVisible(true);
}
}
Radio Button
• Radio buttons are supported by the JRadioButton class, which is a concrete implementation of
AbstractButton.
• Some of its constructors are :
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
• Here, i is the icon for the button. The text is specified by s. If state is true, the button is ininitially
selected. Otherwise, it is not.
• Elements are then added to the button group via the following method:
void add(AbstractButton ab)
• Here, ab is a reference to the button to be added to the group.
Example: Radio button // Add ActionListener to radio buttons
ActionListener listener = new ActionListener() {
@Override
import javax.swing.*;
public void actionPerformed(ActionEvent e) {
import java.awt.*;
String selectedLanguage = ((JRadioButton)
import java.awt.event.ActionEvent;
e.getSource()).getText();
import java.awt.event.ActionListener;
label.setText("Selected Language: " +
public class RadioButtonExample {
selectedLanguage);
public static void main(String[] args) {
}
// Create a new JFrame
};
JFrame frame = new JFrame("JRadioButton Example");
javaButton.addActionListener(listener);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pythonButton.addActionListener(listener);
frame.setSize(400, 200);
cppButton.addActionListener(listener);
frame.setLayout(new FlowLayout());
// Add components to the frame
// Create a JLabel to display the selected choice
frame.add(label);
JLabel label = new JLabel("Select your preferred
frame.add(javaButton);
programming language:");
frame.add(pythonButton);
// Create JRadioButtons
frame.add(cppButton);
JRadioButton javaButton = new JRadioButton("Java");
// Make the frame visible
JRadioButton pythonButton = new JRadioButton("Python");
frame.setVisible(true);
JRadioButton cppButton = new JRadioButton("C++");
}
// Group the radio buttons
}
ButtonGroup group = new ButtonGroup();
group.add(javaButton);
group.add(pythonButton);
group.add(cppButton);
Tables
• A table is a component that displays rows and columns of data. You can drag the cursor on column boundaries
to resize columns. You can also drag a column to a new position.
• Tables are implemented by the JTable class, which extends JComponent.
• One of its constructors is :
JTable(Object data[ ][ ], Object colHeads[ ])
• Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional
array with the column headings.
• Here are the steps for using a table in an applet:
1. Create a JTable object.
2. Create a JScrollPane object. (The arguments to the constructor specify the table and
the policies for vertical and horizontal scroll bars.)
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane of the applet.
Example: Tables // Add the table to a JScrollPane for scrolling
JScrollPane scrollPane = new JScrollPane(table);
// Add components to the frame
import javax.swing.*;
frame.add(scrollPane, BorderLayout.CENTER);
import java.awt.*;
// Set the frame visibility
public class TableExample {
frame.setVisible(true);
public static void main(String[] args) {
}
// Create a JFrame
}
JFrame frame = new JFrame("JTable Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
// Create column names for the table
String[] columnNames = { "ID", "Name", "Age",
"Department" };
// Create data for the table
Object[][] data = {
{ "1", "Alice", "22", "Engineering" },
{ "2", "Bob", "25", "Marketing" },
{ "3", "Charlie", "30", "Finance" },
{ "4", "Diana", "28", "Human Resources" }
};
// Create the JTable with data and column names
JTable table = new JTable(data, columnNames);
// Set table properties
table.setRowHeight(25); // Set row height
choices
• The Choice class is used to create a pop-up list of items from which the user may choose.
• A Choice control is a form of menu.
• Choice only defines the default constructor, which creates an empty list.
• To add a selection to the list, call addItem( ) or add( ).
void addItem(String name)
void add(String name)
• Here, name is the name of the item being added.
• Items are added to the list in the order to determine which item is currently selected, you may
call either getSelectedItem( ) or getSelectedIndex( ).
String getSelectedItem( )
int getSelectedIndex( )

L 6.7
Combo Box
• Swing provides a combo box (a combination of a text field and a drop-down list) through the
JComboBox class, which extends JComponent.
• A combo box normally displays one entry. However, it can also display a drop-down list that al-
lows a user to select a different entry. You can also type your selection into the text field.
• Two of JComboBox's constructors are :
JComboBox( )
JComboBox(Vector v)
• Here, v is a vector that initializes the combo box.
• Items are added to the list of choices via the addItem( ) method, whose signature is:
void addItem(Object obj)
• Here, obj is the object to be added to the combo box.
Example: Combo box comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
import javax.swing.*;
String selectedLanguage = (String)
import java.awt.*;
comboBox.getSelectedItem();
import java.awt.event.ActionEvent;
selectedLabel.setText("Selected Language: " +
import java.awt.event.ActionListener;
selectedLanguage);
public class ComboBoxExample {
}
public static void main(String[] args) {
});
// Create a new JFrame
// Make the frame visible
JFrame frame = new JFrame("JComboBox Example");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
frame.setSize(400, 200);
}
frame.setLayout(new FlowLayout());
// Create an array of items for the JComboBox
String[] languages = { "Java", "Python", "C++",
"JavaScript", "Ruby" };
// Create a JComboBox and add items
JComboBox<String> comboBox = new
JComboBox<>(languages);
// Add the JComboBox to the frame
frame.add(new JLabel("Select a Programming
Language:"));
frame.add(comboBox);
// Create a JLabel to display the selected item
JLabel selectedLabel = new JLabel("Selected Language:
");
frame.add(selectedLabel);
// Add an ActionListener to handle item selection
Layout Manager types

The LayoutManagers are used to arrange components in a particular manner. LayoutManager


is an interface that is implemented by all the classes of layout managers. There are following
classes that represents the layout managers:

java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
BorderLayout

The BorderLayout provides five constants for each region:


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

Constructors of BorderLayout class:


o BorderLayout(): creates a border layout but with no gaps between the components.
o JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.
Example of BorderLayout class:
import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{
f=new JFrame();
JButton b1=new JButton("NORTH");
JButton b2=new JButton("SOUTH");
JButton b3=new JButton("EAST");
JButton b4=new JButton("WEST");
JButton b5=new JButton("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);
}
public static void main(String[] args)
{
new Border();
}}
GridLayout
The GridLayout is used to arrange the components in rectangular grid. One
component is displayed in each rectangle.

Constructors of GridLayout class


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows
and columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with
the given rows and columns alongwith given horizontal and vertical gaps.
Example of GridLayout class
import java.awt.*; f.add(b1);
import javax.swing.*; public class f.add(b2);
MyGridLayout{ JFrame f; f.add(b3);
MyGridLayout(){ f=new JFrame(); f.add(b4);
JButton b1=new JButton("1"); f.add(b5);
f.add(b6);
JButton b2=new JButton("2"); f.add(b7);
JButton b3=new JButton("3"); f.add(b8);
JButton b4=new JButton("4"); f.add(b9);
f.setLayout(new GridLayout(3,3));
JButton b5=new JButton("5");
JButton b6=new JButton("6"); //setting grid layout of 3 rows and 3
JButton b7=new JButton("7"); columns
f.setSize(300,300);
JButton b8=new JButton("8"); f.setVisible(true);
JButton b9=new JButton("9"); }
public static void main(String[] args) {
new MyGridLayout(); }}
GridBag Layout
• The Grid bag layout displays components subject to the constraints specified by
GridBagConstraints.

L 9.7
Example: GridBagLayout JButton button3 = new JButton("Button 3");
gbc.gridx = 0; // Column 0
gbc.gridy = 1; // Row 1
import javax.swing.*; gbc.gridwidth = 1; // Span 1 column
import java.awt.*; gbc.gridheight = 2; // Span 2 rows
public class GridBagLayoutExample { frame.add(button3, gbc);
public static void main(String[] args) { JButton button4 = new JButton("Button 4");
// Create a new JFrame gbc.gridx = 1; // Column 1
JFrame frame = new JFrame("GridBagLayout Example"); gbc.gridy = 1; // Row 1
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gbc.gridwidth = 2; // Span 2 columns
frame.setSize(400, 300); gbc.gridheight = 1; // Span 1 row
// Set GridBagLayout for the frame frame.add(button4, gbc);
frame.setLayout(new GridBagLayout()); JButton button5 = new JButton("Button 5");
GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 1; // Column 1
// Add components to the frame using GridBagLayout gbc.gridy = 2; // Row 2
gbc.gridwidth = 1; // Span 1 column
JButton button1 = new JButton("Button 1");
gbc.gridheight = 1; // Span 1 row
gbc.gridx = 0; // Column 0
frame.add(button5, gbc);
gbc.gridy = 0; // Row 0 JButton button6 = new JButton("Button 6");
gbc.gridwidth = 1; // Span 1 column gbc.gridx = 2; // Column 2
gbc.gridheight = 1; // Span 1 row gbc.gridy = 2; // Row 2
gbc.weightx = 1.0; // Expand horizontally gbc.gridwidth = 1; // Span 1 column
gbc.weighty = 1.0; // Expand vertically gbc.gridheight = 1; // Span 1 row
gbc.fill = GridBagConstraints.BOTH; // Fill both frame.add(button6, gbc);
directions // Make the frame visible
frame.add(button1, gbc); frame.setVisible(true);
JButton button2 = new JButton("Button 2"); }
gbc.gridx = 1; // Column 1 }
gbc.gridy = 0; // Row 0
gbc.gridwidth = 2; // Span 2 columns
gbc.gridheight = 1; // Span 1 row
frame.add(button2, gbc);
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel.
Constructors of FlowLayout class
Fields of FlowLayout class 1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
public static final int LEFT horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5
public static final int RIGHT unit horizontal and vertical gap.
public static final int CENTER 3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

import java.awt.*;
import javax.swing.*;
public class MyFlowLayout
{
JFrame f;
MyFlowLayout()
{
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");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}}
Card layout
• The CardLayout class is unique among the other layout managers in that it stores
several different layouts.
• Each layout can be thought of as being on a separate index card in a deck that can
be shuffled so that any card is on top at a given time.
• CardLayout provides these two constructors:
CardLayout( )
CardLayout(int horz, int vert)
• The cards are held in an object of type Panel. This panel must have CardLayout
selected as its layout manager.
• Cards are added to panel using
void add(Component panelObj, Object name);
• methods defined by CardLayout:
void first(Container deck)
void last(Container deck)
void next(Container deck)
void previous(Container deck)
void show(Container deck, String cardName)
L 9.6
Example: CardLayout
// Add ActionListeners to buttons
import javax.swing.*; btnNext.addActionListener(new ActionListener() {
import java.awt.*;
import java.awt.event.*; public void actionPerformed(ActionEvent e) {
public class CardLayoutExample { cardLayout.next(cardPanel);
public static void main(String[] args) { }
// Create a JFrame });
JFrame frame = new JFrame("CardLayout Example");
btnPrevious.addActionListener(new
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ActionListener() {
frame.setSize(400, 300);
// Create a JPanel with CardLayout public void actionPerformed(ActionEvent e) {
JPanel cardPanel = new JPanel(); cardLayout.previous(cardPanel);
CardLayout cardLayout = new CardLayout(); }
cardPanel.setLayout(cardLayout); });
JPanel card1 = new JPanel();
card1.setBackground(Color.CYAN); JPanel controlPanel = new JPanel();
card1.add(new JLabel("This is Card 1")); controlPanel.add(btnPrevious);
JPanel card2 = new JPanel(); controlPanel.add(btnNext);
card2.setBackground(Color.YELLOW); frame.setLayout(new BorderLayout());
card2.add(new JLabel("This is Card 2"));
JPanel card3 = new JPanel(); frame.add(cardPanel, BorderLayout.CENTER);
card3.setBackground(Color.LIGHT_GRAY); frame.add(controlPanel, BorderLayout.SOUTH);
card3.add(new JLabel("This is Card 3")); // Make the frame visible
// Add cards to the cardPanel frame.setVisible(true);
cardPanel.add(card1, "Card 1");
}
cardPanel.add(card2, "Card 2");
cardPanel.add(card3, "Card 3"); }
JButton btnNext = new JButton("Next");
JButton btnPrevious = new JButton("Previous");
What is an event handling?
• Event Handling is the mechanism that controls the event and decides
what should happen if an event occurs.
• Java Uses the Delegation Event Model to handle the events.
Delegation Event Model
There are mainly three parts in delegation event
model.
• Events : An event is a change of state of an object.
• Events Source : Event source is an object that
generates an event.
• Listeners : A listener is an object that listens to the
event. A listener gets notified when an event
occurs.
Sources generating events
Source Generated Event Listener Interface
Button ActionEvent ActionListener
TextField ActionEvent, TextEvent ActionListener, TextListener
Checkbox ItemEvent ItemListener

Mouse MouseEvent, MouseWheelEvent MouseListener,MouseWheelListener

Keyboard KeyEvent KeyListener


Window WindowEvent WindowListener
Component ComponentEvent ComponentListener
Focus FocusEvent FocusListener
Container ContainerEvent ContainerListener
Scrollbar AdjustmentEvent AdjustmentListener
Choice, RadioButton ItemEvent ItemListener
Event Listener interface Event Listener Methods

ActionListener actionPerformed(ActionEvent evt)

AdjustmentListener adjustmentValueChanged(AjustmentEvent evt)

ItemListener itemStateChanged(ItemEvent evt)

TextListener textValueChanged(TextEvent evt)

componentHidden(ComponentEvent evt),
componentMoved(ComponentEvent evt),
ComponentListener
componentResized(ComponentEvent evt),
componentShown(ComponentEvent evt)

componentAdded(ContainerEvent evt),
ContainerListener
componentRemoved(ContainerEvent evt)

focusGained(FocusEvent evt),
FocusListener
focusLost(FocusEvent evt)
keyPressed(KeyEvent evt),
KeyListener keyReleased(KeyEvent evt),
keyTyped(KeyEvent evt)
mouseClicked(MouseEvent evt),
mouseEntered(MouseEvent evt),
MouseListener mouseExited(MouseEvent evt),
mousePressed(MouseEvent evt),
mouseReleased(MouseEvent evt)

mouseDragged(MouseEvent evt),
MouseMotionListener
mouseMoved(MouseEvent evt)

windowActivated(WindowEvent evt),
windowClosed(WindowEvent evt),
windowClosing(WindowEvent evt),
WindowListener windowDeactivated(WindowEvent evt),
windowDeiconified(WindowEvent evt),
windowIconified(WindowEvent evt),
windowOpened(WindowEvent evt)
A complete example for eventlisteners @Override
public void focusGained(FocusEvent e) {
import javax.swing.*; System.out.println("TextField gained focus");
import java.awt.*; }
import java.awt.event.*; @Override
public class SwingEventDemoWithoutLambda { public void focusLost(FocusEvent e) {
public static void main(String[] args) { System.out.println("TextField lost focus");
// Create the main frame }
JFrame frame = new JFrame("Enhanced Swing Event });
Demo"); frame.add(textField);
frame.setSize(600, 600); // Checkbox (ItemEvent)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE JCheckBox checkBox = new JCheckBox("Accept Terms");
); checkBox.addItemListener(new ItemListener() {
frame.setLayout(new FlowLayout()); @Override
// Button (ActionEvent) public void itemStateChanged(ItemEvent e) {
JButton button = new JButton("Click Me"); System.out.println("Checkbox state changed: " +
button.addActionListener(new ActionListener() { checkBox.isSelected());
@Override }
public void actionPerformed(ActionEvent e) { });
JOptionPane.showMessageDialog(frame, "Button frame.add(checkBox);
clicked!"); // Choice (ItemEvent)
} JComboBox<String> comboBox = new JComboBox<>(new
}); String[]{"Option 1", "Option 2", "Option 3"});
frame.add(button); comboBox.addItemListener(new ItemListener() {
// TextField (ActionEvent and FocusEvent) @Override
JTextField textField = new JTextField(20); public void itemStateChanged(ItemEvent e) {
textField.addActionListener(new ActionListener() { System.out.println("Selected: " +
@Override comboBox.getSelectedItem());
public void actionPerformed(ActionEvent e) { }
JOptionPane.showMessageDialog(frame, "Enter pressed });
in text field!"); frame.add(comboBox);
}
// Radio Buttons (ItemEvent) frame.add(scrollBar);
JRadioButton rb1 = new JRadioButton("Male"); // MouseListener and MouseMotionListener
JRadioButton rb2 = new JRadioButton("Female"); JLabel mouseLabel = new JLabel("Move or click the
ButtonGroup group = new ButtonGroup(); mouse here");
group.add(rb1); mouseLabel.setPreferredSize(new Dimension(200, 50));
group.add(rb2); mouseLabel.setOpaque(true);
rb1.addItemListener(new ItemListener() { mouseLabel.setBackground(Color.LIGHT_GRAY);
@Override mouseLabel.addMouseListener(new MouseListener() {
public void itemStateChanged(ItemEvent e) { @Override
System.out.println("Male selected: " + public void mouseClicked(MouseEvent e) {
rb1.isSelected()); System.out.println("Mouse clicked at: " +
} e.getPoint());
}); }
rb2.addItemListener(new ItemListener() { @Override
@Override public void mousePressed(MouseEvent e) {
public void itemStateChanged(ItemEvent e) { System.out.println("Mouse pressed at: " +
System.out.println("Female selected: " + e.getPoint());
rb2.isSelected()); }
} @Override
}); public void mouseReleased(MouseEvent e) {
frame.add(rb1); System.out.println("Mouse released at: " +
frame.add(rb2); e.getPoint());
// ScrollBar (AdjustmentEvent) }
JScrollBar scrollBar = new @Override
JScrollBar(JScrollBar.HORIZONTAL, 50, 10, 0, 100); public void mouseEntered(MouseEvent e) {
scrollBar.addAdjustmentListener(new mouseLabel.setBackground(Color.YELLOW);
AdjustmentListener() { System.out.println("Mouse entered the label");
@Override }
public void adjustmentValueChanged(AdjustmentEvent @Override
e) { public void mouseExited(MouseEvent e) {
System.out.println("Scrollbar value: " + mouseLabel.setBackground(Color.LIGHT_GRAY);
scrollBar.getValue()); System.out.println("Mouse exited the label");
// WindowListener
mouseLabel.addMouseMotionListener(new
frame.addWindowListener(new WindowListener() {
MouseMotionListener() {
@Override
@Override
public void windowOpened(WindowEvent e) {
public void mouseMoved(MouseEvent e) {
System.out.println("Window opened");
System.out.println("Mouse moved at: " + e.getPoint());
}
}
@Override
@Override
public void windowClosing(WindowEvent e) {
public void mouseDragged(MouseEvent e) {
System.out.println("Window is closing");
System.out.println("Mouse dragged at: " +
}
e.getPoint());
@Override
}
public void windowClosed(WindowEvent e) {
});
System.out.println("Window closed");
frame.add(mouseLabel);
}
// KeyListener
@Override
JTextArea textArea = new JTextArea(5, 20);
public void windowIconified(WindowEvent e) {
textArea.addKeyListener(new KeyListener() {
System.out.println("Window minimized");
@Override
}
public void keyPressed(KeyEvent e) {
@Override
System.out.println("Key pressed: " +
public void windowDeiconified(WindowEvent e) {
KeyEvent.getKeyText(e.getKeyCode()));
System.out.println("Window restored");
}
}
@Override
@Override
public void keyReleased(KeyEvent e) {
public void windowActivated(WindowEvent e) {
System.out.println("Key released: " +
System.out.println("Window activated");
KeyEvent.getKeyText(e.getKeyCode()));
}
}
@Override
@Override
public void windowDeactivated(WindowEvent e) {
public void keyTyped(KeyEvent e) {
System.out.println("Window deactivated");
System.out.println("Key typed: " + e.getKeyChar());
}
}
});
});
// ComponentListener
frame.addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent e) {
System.out.println("Frame resized to: " +
frame.getSize());
}
@Override
public void componentMoved(ComponentEvent e) {
System.out.println("Frame moved to: " +
frame.getLocation());
}
@Override
public void componentShown(ComponentEvent e) {
System.out.println("Frame is now visible");
}
@Override
public void componentHidden(ComponentEvent e) {
System.out.println("Frame is now hidden");
}
});
// Display the frame
frame.setVisible(true);
}
}
Now play with the above frame to understand the
functionalities of various controls and
events/eventslisteners/eventhandlers
Java Network
Programming
Increased demand for Internet applications
• To take advantage of opportunities presented by the
Internet, businesses are continuously seeking new and
innovative ways and means for offering their services via
the Internet.
• This created a huge demand for software designers with
skills to create new Internet-enabled applications or
migrate existing applications on the Internet platform.
• Object-oriented Java technologies—Sockets, threads,
RMI, Web services, etc.-- have emerged as leading
solutions for creating portable, efficient, and maintainable
large and complex Internet applications.
Elements of Client-Server
Computing
a client, a server, and network

t
es
qu
X

Re
Client
Server
Network
Re
su
lt

Client machine
Server machine
Networking Basics
• Computers running on the Internet communicate with each other
using either the Transmission Control Protocol (TCP) or the User
Datagram Protocol (UDP)

• Internet Protocol (IP) is a low-level routing protocol that breaks


data into small packets and sends them to an address across a
network, which does not guarantee to deliver said packets to the
destination.
• Transmission Control Protocol (TCP) is a higher-level protocol
that manages to robustly string together these packets, sorting
and retransmitting them as necessary to reliably transmit data.

• User Datagram Protocol (UDP), sits next to TCP and can be used
directly to support fast, connectionless, unreliable transport of
packets. 72
DNS - Domain name system
• The Domain Name system (DNS) associates various sorts of information
with so-called domain names.

• Most importantly, it serves as the "phone book" for the Internet by


translating human-readable computer hostnames, e.g. www.example.com,
into the IP addresses, e.g. 208.77.188.166, that networking equipment
needs to deliver information.

73
Understanding Ports
• The TCP and UDP protocols use ports to map incoming data to a
particular process running on a computer.

app app app app

port port port port

TCP or UDP
Packet
Data port# data
Understanding Ports
• Port is represented by a positive (16-bit) integer value
• Some ports have been reserved to support common/well known
services:
• ftp 21/tcp (for sharing files)
• telnet 23/tcp (for remote connection b/w client and server over LAN/Internet)
• smtp 25/tcp (for sending/receiving e-mails)
• whois 43/tcp (used to gather details about a domain name or IP address)
• http 80/tcp (for accessing websites)
• User level process/services generally use port number value >= 1024
Sockets
• At the core of Java’s networking support is the concept of a
socket.

• A socket identifies an endpoint in a network.

• Sockets allows a single computer to serve many different


clients at once, as well as to serve many different types of
information.

• This is accomplished through the use of a port, which is a


numbered socket on a particular machine.
Transmission Control Protocol
• A connection-based protocol that provides a reliable flow
of data between two computers.
• Provides a point-to-point channel for applications that
require reliable communications.
• The Hypertext Transfer Protocol (HTTP), File Transfer Protocol
(FTP), and Telnet are all examples of applications that require a
reliable communication channel
• Guarantees that data sent from one end of the
connection actually gets to the other end and in the same
order it was sent. Otherwise, an error is reported.
User Datagram Protocol
• A protocol that sends independent packets of data,
called datagrams, from one computer to another with
no guarantees about arrival. UDP is not connection-
based like TCP and is not reliable:
• Sender does not wait for acknowledgements
• Arrival order is not guaranteed
• Arrival is not guaranteed
• Used when speed is essential, even in cost of reliability
• e.g. streaming media, games, Internet telephony, etc.
Ports
• Data transmitted over the Internet is accompanied by addressing
information that identifies the computer and the port for which it is
destined.
• The computer is identified by its 32-bit IP address, which IP uses to deliver
data to the right computer on the network. Ports are identified by a 16-bit
number, which TCP and UDP use to deliver the data to the right application.
Networking Classes in the JDK
• Through the classes in java.net, Java programs can use TCP or UDP to
communicate over the Internet.
• The InetAddress, URL, URLConnection, Socket, and
ServerSocket classes all use TCP to communicate over the network.
• The DatagramPacket, DatagramSocket, and MulticastSocket
classes are for use with UDP.

80
TCP/IP in Java
• Accessing TCP/IP from Java is straightforward. The
main functionality is in the following classes:
• java.net.InetAddress : Represents an IP address
(either IPv4 or IPv6) and has methods for performing DNS
lookup.
• java.net.Socket : Represents a TCP socket.
• java.net.ServerSocket : Represents a server socket
which is capable of waiting for requests from clients.

81
InetAddress
• The InetAddress class is used to encapsulate both the numerical IP
address and the domain name for that address.
• We interact with this class by using the name of an IP host, which is
more convenient and understandable than its IP address.
• The InetAddress class hides the number inside.
Factory Methods
factory methods are merely a convention whereby static methods in a class return an
instance of that class.

• static InetAddress getLocalHost( )


throws UnknownHostException
• static InetAddress getByName(String hostName)
throws UnknownHostException
• static InetAddress[ ] getAllByName(String hostName)
throws UnknownHostException
Example:
class InetAddressTest
{
public static void main(String args[])
throws UnknownHostException
{
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("www.google.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.yahoo.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}
Instance Methods
class InetAddressTest1
{
public static void main(String args[])
throws UnknownHostException
{
InetAddress Address =
InetAddress.getByName("www.google.com");
System.out.println(Address.getHostAddress());
System.out.println(Address.getHostName());
if(Address.isMulticastAddress())
System.out.println("It is multicast address");
}
}
Sockets and Java Socket Classes
• A socket is an endpoint of a two-way communication link between
two programs running on the network.
• A socket is bound to a port number so that the TCP layer can identify
the application that data destined to be sent.
• TCP/IP sockets are used to implement reliable, bidirectional,
persistent, point-to-point, stream-based connections between hosts
on the Internet.
• Java’s .net package provides two classes:
• Socket – for implementing a client
• ServerSocket – for implementing a server
86
Java Sockets
Server ServerSocket(1234)

Output/write stream Client

Input/read stream

Socket(“128.250.25.158”, 1234)

It can be host_name like “books.google.com”


Client Sockets
• Java wraps OS sockets (over TCP) by the
objects of class java.net.Socket
Socket(String remoteHost, int
remotePort)
• Creates a TCP socket and connects it to the
remote host on the remote port (hand
shake)
• Write and read using streams:
– InputStream getInputStream()
– OutputStream getOutputStream()

88
Constructors
• Socket(String remoteHost, int remotePort)

• Socket(InetAddress ip, int remotePort)


Implementing a Client
1. Create a Socket Object:
client = new Socket( server, port_id );
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());
3. Perform I/O or communication with the server:
• Receive data from the server:
String line = is.readLine();
• Send data to the server:
os.writeBytes("Hello\n");
4. Close the socket when done:
client.close();
Example: Whois server
class Whois
{
public static void main(String args[ ]) throws Exception
{
int c;
Socket s = new Socket("internic.net", 43);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
String str="google.com\n";
byte buf[] = str.getBytes();
out.write(buf);
while ((c = in.read()) != -1)
System.out.print((char) c);
s.close();
}
}
ServerSocket
• This class implements server sockets. A server socket waits for
requests to come in over the network. It performs some operation
based on that request, and then possibly returns a result to the
requester.

92
Constructors
• ServerSocket (int port) throws BindException, IOException
Use for basic servers that listen on all interfaces.

• ServerSocket (int port, int maxQueue) throws BindException, IOException


Use when you want to limit the connection queue size explicitly.

• ServerSocket (int port, int maxQ, InetAddress ip) throws IOException


Use for advanced scenarios where the server needs to bind to a specific network
interface or IP address.
Implementing a Server
• Open the Server Socket:
ServerSocket server;
DataOutputStream os;
DataInputStream is;
server = new ServerSocket( PORT );
X • Wait for the Client Request:
Socket client = server.accept();
• Create I/O streams for communicating to the
client
is = new
DataInputStream(client.getInputStream() );
os = new
DataOutputStream(client.getOutputStream());
• Perform communication with client
Receive from client: String line =
is.readLine();
Client-Server Interaction via
TCP
Client-server communication
example
SERVER Class
// Communication loop
String clientMessage;
import java.io.*; while ((clientMessage = reader.readLine())
import java.net.*; != null) {
public class Server { System.out.println("Received from client:
public static void main(String[] args) { " + clientMessage);
int port = 9090; // Echo the message back to the client
try (ServerSocket serverSocket = new String response = "Server: " +
ServerSocket(port)) { clientMessage.toUpperCase();
System.out.println("Server is listening on writer.println(response);
port " + port);
if ("bye".equalsIgnoreCase(clientMessage))
// Wait for a client connection
{
Socket socket = serverSocket.accept();
System.out.println("Client connected: " + System.out.println("Client
socket.getInetAddress()); disconnected.");
// Create input and output streams break;
InputStream input = }}
socket.getInputStream(); // Clean up
BufferedReader reader = new socket.close();
BufferedReader(new System.out.println("Server stopped.");
InputStreamReader(input)); } catch (IOException ex) {
OutputStream output = System.out.println("Server exception: " +
socket.getOutputStream(); ex.getMessage());
PrintWriter writer = new ex.printStackTrace();
PrintWriter(output, true); }}}
Client-server communication
example
Client Class
while (true) {
System.out.print("Enter message: ");
import java.io.*; userInput = consoleReader.readLine();
import java.net.*; // Send message to the server
public class Client { writer.println(userInput);
public static void main(String[] args) {
String hostname = "127.0.0.1";
// Receive response from the server
int port = 9090; String serverResponse =
try (Socket socket = new Socket(hostname, reader.readLine();
port)) { System.out.println(serverResponse);
System.out.println("Connected to the if ("bye".equalsIgnoreCase(userInput)) {
server."); System.out.println("Disconnected from
// Create input and output streams server.");
InputStream input = socket.getInputStream(); break;
BufferedReader reader = new }
BufferedReader(new InputStreamReader(input)); }
OutputStream output = // Clean up
socket.getOutputStream(); socket.close();
PrintWriter writer = new PrintWriter(output,
} catch (UnknownHostException ex) {
true);
// Communication loop System.out.println("Server not found: " +
BufferedReader consoleReader = new ex.getMessage());
BufferedReader(new } catch (IOException ex) {
InputStreamReader(System.in)); System.out.println("I/O error: " +
String userInput; ex.getMessage());
}}}
TCP vs. UDP
No. TCP UDP
1 This Connection oriented protocol This is connection-less protocol
The TCP connection is byte stream The UDP connection is a message stream
2

It does not support multicasting and It supports broadcasting


3 broadcasting

It provides error control and flow control The error control and flow control is not
4 provided

TCP supports full duplex transmission UDP does not support full duplex
5 transmission

It is reliable service of data transmission This is an unreliable service of data


6 transmission

The TCP packet is called as segment The UDP packet is called as user
7 datagram.
Thank You
Reference Links

Java Concepmap by Programiz


https://www.programiz.com/java-programming

Reference Material


Thank you
javac --release 8 MyClass.java

You might also like