Java Module4
Java Module4
•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
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
//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).
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 setSize(int width,int sets the size (width and height) of the
height) component.
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.
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
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.
We can write the code of swing inside the main(), constructor or any other method.
import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
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.
Constructor Description
Methods Description
Constructor Description
Methods Description
Constructor Description
Methods Description
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.
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
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
BorderLayout
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
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)
• 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.
73
Understanding Ports
• The TCP and UDP protocols use ports to map incoming data to a
particular process running on a computer.
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.
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.
Input/read stream
Socket(“128.250.25.158”, 1234)
88
Constructors
• Socket(String remoteHost, int remotePort)
92
Constructors
• ServerSocket (int port) throws BindException, IOException
Use for basic servers that listen on all interfaces.
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
The TCP packet is called as segment The UDP packet is called as user
7 datagram.
Thank You
Reference Links
Reference Material
•
Thank you
javac --release 8 MyClass.java