0% found this document useful (0 votes)
12 views

AJAVAUnit 4

The document provides an overview of the Abstract Window Toolkit (AWT) in Java, detailing its components, containers, layout managers, and event handling capabilities. It explains the structure of AWT packages, the types of containers such as Frame, Dialog, and Panel, and various layout managers like FlowLayout, BorderLayout, and GridLayout. Additionally, it includes code examples demonstrating how to create AWT windows and add components using different layout managers.

Uploaded by

solankiaryamann2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

AJAVAUnit 4

The document provides an overview of the Abstract Window Toolkit (AWT) in Java, detailing its components, containers, layout managers, and event handling capabilities. It explains the structure of AWT packages, the types of containers such as Frame, Dialog, and Panel, and various layout managers like FlowLayout, BorderLayout, and GridLayout. Additionally, it includes code examples demonstrating how to create AWT windows and add components using different layout managers.

Uploaded by

solankiaryamann2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Unit IV

Abstract Window Toolkit (AWT)

AWT is the foundation upon which Swing is made i.e Swing is a improved GUI API that extends
the AWT. AWT provides various components like button, label, checkbox, etc. used as objects
inside a Java Program. But now a days AWT is merely used because most GUI Java programs
are implemented using Swing because of its rich implementation of GUI controls and light-
weighted nature. The Libraries of AWT are written in Java which they are totally platform-
independent

AWT Packages

1. The java.awt package contains the core AWT graphics classes:


(i) GUI Component classes, such as Button, TextField, and Label.
(ii) GUI Container classes, such as Frame and Panel.
(iii) Layout managers, such as FlowLayout, BorderLayout and GridLayout.
(iv) Custom graphics classes, such as Graphics, Color and Font.
2. The java.awt.event package supports event handling:
(i) Event classes, such as ActionEvent, MouseEvent, KeyEvent and WindowEvent,
(ii)Event Listener Interfaces, such as ActionListener, MouseListener,
MouseMotionListener, KeyListener and WindowListener,
(iii) Event Listener Adapter classes, such as MouseAdapter, KeyAdapter, and
WindowAdapter.
AWT Hierarchy
 Components: AWT provides various components such as buttons, labels, text fields,
checkboxes, etc used for creating GUI elements for Java Applications.
 Containers: AWT provides containers like panels, frames, and dialogues to organize and
group components in the Application.
 Layout Managers: Layout Managers are responsible for arranging data in the containers
sone of the layout managers are BorderLayout, FlowLayout, etc.
 Event Handling: AWT allows the user to handle the events like mouse clicks, key presses,
etc. using event listeners and adapters.
 Graphics and Drawing: It is the feature of AWT that helps to draw shapes, insert images
and write text in the components of a Java Application.

Containers in Java AWT


There are four types of containers in Java AWT:
1. Window: Window is a top-level container that represents a graphical window or dialog box.
The Window class extends the Container class, which means it can contain other
components, such as buttons, labels, and text fields.
2. Frame: The Frame is the container that contains the title bar and border and can have menu
bars.
3. Dialog: A dialog box is a temporary window an application creates to retrieve user input.
4. Panel: The Panel is the container that doesn't contain title bar, border or menu bar. It is a
lightweight container that can be used for grouping other components together within a
window or a frame.

Components in Java AWT: AWT provides various components such as buttons, labels, text
fields, checkboxes, etc used for creating GUI elements for Java Applications.

Creating an AWT Window


import java.awt.*;
public class MyAWTWindow {
public static void main(String[] args) {
// Create a new frame (window)
Frame myFrame = new Frame("My AWT Window");

// Set the size of the frame


myFrame.setSize(400, 300);//width, height

// Make the frame visible


myFrame.setVisible(true);
}
}

Adding Components to the Window:

Example1

import java.awt.*;
public class MyAWTContainerDemo {
public static void main(String[] args) {
Frame myFrame = new Frame("Container Example");
Panel p1 = new Panel();
Button button1 = new Button("Button 1");
Button button2 = new Button("Button 2");
p1.add(button1);
p1.add(button2);
p1.setBackground(Color.CYAN);
myFrame.add(p1, BorderLayout.NORTH);
myFrame.setSize(400, 300);
myFrame.setVisible(true);
}
} Output:

Example2
import java.awt.*;
import java.applet.*;
/*
<applet code = "LabelDemo" width=300 height=200>
</applet>
*/
public class LabelDemo extends Applet
{
public void init ()
{
Label one = new Label ("Hari");
Label two = new Label ("Mohan");
Label three = new Label ("Mishra");
add (one);
add (two);
add (three);
}
}
Output:

Example3
import java.awt.*;
public class ButtonExample extends Frame{
ButtonExample()
{

Button button = new Button("Click Here");


add(button); // Add the button to the frame
setSize(300, 300); // Set frame size
setVisible(true); // Make the frame visible
}
public static void main(String[] args) {
new ButtonExample();
}
}
Output

LayoutManager and types of LayoutManager

The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout managers.
There are the following types of layout managers:

 FlowLayout: It arranges the components in a container like the words on a page. It fills
the top line from left to right and top to bottom.
 BorderLayout: It arranges all the components along the edges or the middle of the
container i.e. top, bottom, right and left edges of the area.
 GridLayout: It arranges all the components in a grid of equally sized cells, adding them
from the left to right and top to bottom.
 BoxLayout: It arranges multiple components in either vertically or horizontally, but not
both. The components are arranged from left to right or top to bottom.
 CardLayout: It arranges two or more components having the same size. The components
are arranged in a deck, where all the cards of the same size and the only top card are
visible at any time. The first component added in the container will be kept at the top of
the deck.

java.awt.FlowLayout,
java.awt.BorderLayout ,
java.awt.GridLayout,
javax.swing.BoxLayout,
java.awt.CardLayout

FlowLayout

Fields of FlowLayout class


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

Example
import java.awt.*;
import javax.swing.*;

public class FlowLayoutExample


{

JFrame frameObj;

// constructor
FlowLayoutExample()
{
// creating a frame object
frameObj = new JFrame();

// creating the buttons


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

// adding the buttons to frame


frameObj.add(b1);
frameObj.add(b2);
frameObj.add(b3);
frameObj.add(b4);
frameObj.add(b5);
// parameter less constructor is used
// therefore, alignment is center
// horizontal as well as the vertical gap is 5 units.
frameObj.setLayout(new FlowLayout(FlowLayout.RIGHT)); //
//frameObj.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 25));

frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}
Output

Example of BorderLayout class


Fields of BorderLayout class

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 BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.

import java.awt.*;

public class Border


{
Frame f;
Border()
{
f = new Frame();
// creating buttons
Button b1 = new Button("NORTH");; // the button will be labeled as NORTH
Button b2 = new Button("SOUTH");; // the button will be labeled as SOUTH
Button b3 = new Button("EAST");; // the button will be labeled as EAST
Button b4 = new Button("WEST");; // the button will be labeled as WEST
Button b5 = new Button("CENTER");; // the button will be labeled as CENTER

//f.setLayout(new BorderLayout(20, 10));//You can use to provide gap between


controls
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Output

Note:You can also use JFrame and JButton here by importing javax.swing.*;
Example of GridLayout class

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 along with given

import java.awt.*;
//import javax.swing.*;
import java.awt.GridLayout;
class GridLayout1{
Frame frm;

GridLayout1(){
frm=new Frame();

Button btn1=new Button("1");


Button btn2=new Button("2");
Button btn3=new Button("3");
Button btn4=new Button("4");
Button btn5=new Button("5");
Button btn6=new Button("6");

frm.add(btn1);
frm.add(btn2);
frm.add(btn3);
frm.add(btn4);
frm.add(btn5);
frm.add(btn6);
frm.setLayout(new GridLayout(3,2));
frm.setSize(300,300);
frm.setVisible(true);
}
public static void main(String[] arguments) {
new GridLayout1();
}}
Output:
BoxLayout

Fields of BoxLayout Class


1. public static final int X_AXIS: Alignment of the components are horizontal from left to
right.
2. public static final int Y_AXIS: Alignment of the components are vertical from top to
bottom.

Constructor of BoxLayout class


BoxLayout(Container c, int axis): creates a box layout that arranges the components with the
given axis.

Example of BoxLayout class with Y-AXIS:


import java.awt.*;
import javax.swing.*;
public class BoxLayoutExample1 extends Frame {
Button buttons[];
public BoxLayoutExample1 () {
buttons = new Button [5];
for (int i = 0;i<5;i++) {
buttons[i] = new Button ("Button " + (i + 1));
// adding the buttons so that it can be displayed
add (buttons[i]);
}
// the buttons will be placed horizontally
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}
// main method
public static void main(String args[]){
BoxLayoutExample1 b=new BoxLayoutExample1();
}
}
output

Example of BoxLayout class with X-AXIS


import java.awt.*;
import javax.swing.*;

public class BoxLayoutExample2 extends Frame {


Button buttons[];

public BoxLayoutExample2() {
buttons = new Button [5];

for (int i = 0;i<5;i++) {


buttons[i] = new Button ("Button " + (i + 1));
// adding the buttons so that it can be displayed
add (buttons[i]);
}
// the buttons in the output will be aligned vertically
setLayout (new BoxLayout(this, BoxLayout.X_AXIS));
setSize(400,400);
setVisible(true);
}
// main method
public static void main(String args[]){
BoxLayoutExample2 b=new BoxLayoutExample2();
}
}

output

CardLayout

Constructors of CardLayout Class


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.
Commonly Used Methods of CardLayout Class
o public void next(Container parent): is used to flip to the next card of the given
container.
o public void previous(Container parent): is used to flip to the previous card of the given
container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given container.

Example of CardLayout Class: Using Default Constructor


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class CardLayoutExample1 extends JFrame implements ActionListener
{

CardLayout crd;
// button variables to hold the references of buttons
JButton btn1, btn2, btn3;
Container cPane;

// constructor of the class


CardLayoutExample1()
{

cPane = getContentPane();

//default constructor used


// therefore, components will
// cover the whole area
crd = new CardLayout();

cPane.setLayout(crd);

// creating the buttons


btn1 = new JButton("Apple");
btn2 = new JButton("Boy");
btn3 = new JButton("Cat");

// adding listeners to it
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);

cPane.add("a", btn1); // first card is the button btn1


cPane.add("b", btn2); // first card is the button btn2
cPane.add("c", btn3); // first card is the button btn3

}
public void actionPerformed(ActionEvent e)
{
// Upon clicking the button, the next card of the container is shown
// after the last card, again, the first card of the container is shown upon clicking
crd.next(cPane);
}

// main method
public static void main(String argvs[])
{
// creating an object of the class CardLayoutExample1
CardLayoutExample1 crdl = new CardLayoutExample1();

// size is 300 * 300


crdl.setSize(300, 300);
crdl.setVisible(true);
crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output

When the button named apple is clicked, we get Boy and so on..

Example of CardLayout Class: Using Parameterized Constructor


import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
public class CardLayoutExample2 extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample2(){

c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);

b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

c.add("a",b1);c.add("b",b2);c.add("c",b3);

}
public void actionPerformed(ActionEvent e) {
card.next(c);
}

public static void main(String[] args) {


CardLayoutExample2 cl=new CardLayoutExample2();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
} output
The layout managers are used to automatically decide the position and size of the added
components. In the absence of a layout manager, the position and size of the components have to be
set manually. The setBounds() method is used in such a situation to set the position and size. To
specify the position and size of the components manually, the layout manager of the frame can
be null.
setBounds()
The setBounds() method needs four arguments. The first two arguments are x and y coordinates of
the top-left corner of the component, the third argument is the width of the component and the fourth
argument is the height of the component. The setBounds() method is a part of the java.awt.Component class.
Syntax
setBounds(int x-coordinate, int y-coordinate, int width, int height)
Exaample1
import javax.swing.*;
import java.awt.*;
public class SetBoundsTest {
public static void main(String arg[]) {
JFrame frame = new JFrame("SetBounds Method Test");
frame.setSize(375, 250);
// Setting layout as null
frame.setLayout(null);
// Creating Button
JButton button = new JButton("Hello Java");
// Setting position and size of a button
button.setBounds(80,30,120,40);
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output

Example2
// importing Java AWT class
import java.awt.*;
// class AWTExample2 directly creates instance of Frame class
class AWTExample2 {
// initializing using constructor
AWTExample2() {
// creating a Frame
Frame f = new Frame();
// creating a Label
Label l = new Label("Employee id:");
// creating a Button
Button b = new Button("Submit");

// creating a TextField
TextField t = new TextField();

// setting position of above components in the frame


l.setBounds(50, 80, 80, 50);
t.setBounds(50, 100, 80, 50);
b.setBounds(50, 150, 80, 50);

// adding components into frame


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

// frame size 300 width and 300 height


f.setSize(400,300);

// setting the title of frame


f.setTitle("Employee info");

// no layout
f.setLayout(null);

// setting visibility of frame


f.setVisible(true);
}

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

// creating instance of Frame class


AWTExample2 awt_obj = new AWTExample2();

}
Output
Different AWT Components
An AWT component can be considered as an object that can be made visible on a graphical
interface screen and through which interaction can be performed.
In java.awt package, the following components are available:
1. Containers: As the name suggests, this awt component is used to hold other components.
Basically, there are the following different types of containers available in java.awt package:
a. Window: This is a top-level container and an instance of a window class that does not contain
a border or title.
b. Frame: Frame is a Window class child and comprises the title bar, border and menu bars.
Therefore, the frame provides a resizable canvas and is the most widely used container used for
developing AWT-based applications. Various components such as buttons, text fields, scrollbars
etc., can be accommodated inside the frame container.
Java Frame can be created in two ways:
 By Creating an object of Frame class.
 By making Frame class parent of our class.
o Dialog: Dialog is also a child class of window class, and it provides support for
the border as well as the title bar. In order to use dialog as a container, it always
needs an instance of frame class associated with it.
o Panel: It is used for holding graphical user interface components and does not
provide support for the title bar, border or menu.
2. Button: This is used to create a button on the user interface with a specified label. We can
design code to execute some logic on the click event of a button using listeners.
3. Text Fields: This component of java AWT creates a text box of a single line to enter text data.
4. Label: This component of java AWT creates a multi-line descriptive string that is shown on
the graphical user interface.
5. Canvas: This generally signifies an area that allows you to draw shapes on a graphical user
interface.
6. Choice: This AWT component represents a pop-up menu having multiple choices. The option
which the user selects is displayed on top of the menu.
7. Scroll Bar: This is used for providing horizontal or vertical scrolling feature on the GUI.
8. List: This component can hold a list of text items. This component allows a user to choose one
or more options from all available options in the list.
9. Checkbox: This component is used to create a checkbox of GUI whose state can be either
checked or unchecked.
Java Event Handling

Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The java.awt.event package provides many event classes and Listener interfaces for
event handling.

Listeners are created by implementing one or more of the interfaces defined by the
java. awt. event package. When an event occurs, the event source invokes the appropriate
method defined by the listener and provides an event object as its argument

Java Event classes and Listener interfaces


Event Classes Listener Interfaces

ActionEvent(such as a Button click) ActionListener

MouseEvent MouseListener and


MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener
For registering the component with the Listener, many classes provide the registration methods.
For example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

public class ActionEvent extends AWTEvent

Example1
import java.awt.*;
import java.awt.event.*;
class EventDemo extends Frame implements ActionListener{
TextField tf;
EventDemo(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
add(b);
add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
} // overriding the actionPerformed() method of ActionListener interface
public void actionPerformed(ActionEvent e){
tf.setText("Welcome"); // //tf.setText(e.toString());
}
public static void main(String args[]){
new EventDemo();
}
}

Output

When you click on button output will be as

Example2

import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener {
Label l;
TextArea area;
KeyListenerExample() {
l = new Label();
l.setBounds (20, 50, 100, 20);
area = new TextArea();
area.setBounds (20, 80, 300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize (400, 400);
setLayout (null);
setVisible (true);
} // overriding the keyPressed() method of KeyListener interface
public void keyPressed (KeyEvent e) {
l.setText ("Key Pressed");
} // overriding the keyReleased() method of KeyListener interface
public void keyReleased (KeyEvent e) {
l.setText ("Key Released");
} // overriding the keyTyped() method of KeyListener interface
public void keyTyped (KeyEvent e) {
l.setText ("Key Typed");
}
public static void main(String[] args) {
new KeyListenerExample();
}
}
Output

Java AWT Dialog

The Dialog 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 Window class.

Unlike Frame, it doesn't have maximize and minimize buttons.

Frame vs Dialog

Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons but
Dialog doesn't have.
Java AWT Dialog Example
import java.awt.*;
import java.awt.event.*;
public class DialogExample implements ActionListener {
private Dialog d;
DialogExample() {
// Frame f= new Frame();
d = new Dialog(d, "Dialog Example"); // d = new Dialog(f, "Dialog Example");
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener (this);
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ d.setVisible(false);
}
public static void main(String args[])
{
new DialogExample();
}
}
Output

AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a GUI component allows us to
see invisible number of rows and columns.

Scrollbar Class Fields


o static int HORIZONTAL - It is a constant to indicate a horizontal scroll bar.
o static int VERTICAL - It is a constant to indicate a vertical scroll bar.
Scrollbar Class Constructors
Sr. Constructor Description
no.

1 Scrollbar() Constructs a new vertical scroll bar.

2 Scrollbar(int orientation) Constructs a new scroll bar with the specified orientation.

3 Scrollbar(int orientation, int value, Constructs a new scroll bar with the specified orientation, i
int visible, int minimum, int and minimum and maximum values.
maximum)

o orientation: specifiey whether the scrollbar will be horizontal or vertical.


o Value: specify the starting position of the knob of Scrollbar on its track.
o Minimum: specify the minimum width of track on which scrollbar is moving.
o Maximum: specify the maximum width of track on which scrollbar is moving.

Scrollbar Example
import java.awt.*;
public class ScrollbarExample {
// class constructor
ScrollbarExample() {
// creating a frame
Frame f = new Frame("Scrollbar Example");
// creating a scroll bar
Scrollbar s = new Scrollbar();
// setting the position of scroll bar left top width height
s.setBounds (100, 100, 30, 100);
// adding scroll bar to the frame
f.add(s);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setVisible(true);
}
// main method
public static void main(String args[]) {
new ScrollbarExample();
}
}
Output

AWT MenuItem and Menu


The object of MenuItem class adds a simple labeled menu item on menu. The items
used in a menu must belong to the MenuItem or any of its subclass.

The object of Menu class is a pull down menu component which is displayed on the
menu bar. It inherits the MenuItem class.
Menu Example1
import java.awt.*;
import java.awt.event.*;
class MenuExample implements ActionListener
{
Frame f;
Menu mymenu;
MenuItem i1,i2 ;
MenuBar mb;
Dialog d;
MenuExample ()
{
f= new Frame("Menu Example");
mb = new MenuBar();
f.setMenuBar(mb);
mymenu = new Menu("Click");
i1 = new MenuItem("Open");
mymenu.add(i1);
mymenu.addSeparator();
i2= new MenuItem("Exit");
mymenu.add(i2);
i1.addActionListener(this);
i2.addActionListener(this);
mb.add(mymenu);
f.setSize(300, 300);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{

if(e.getSource()==i1){
d=new Dialog (d,"New Window");
d.setSize(300,300);
d.setVisible(true);

}
else if(e.getSource()==i2)
{
System.exit(0);
}
}

public static void main(String[] args)


{
new MenuExample ();

}
}
Output
Menu Example2
import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}
output
Java Swing
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit
[AWT]. Java Swing offers much-improved functionality over AWT, new components, expanded
components features, and excellent event handling with drag-and-drop support.
What is JFC?
JFC stands for Java Foundation Classes. JFC is the set of GUI components that simplify desktop
Applications. Many programmers think that JFC and Swing are one and the same thing, but that is
not so. JFC contains Swing [A UI component package] and quite a number of other items:
 Cut and paste: Clipboard support.
 Accessibility features: Aimed at developing GUIs for users with disabilities.
 The Desktop Colors Features were first introduced in Java 1.1
 Java 2D: it has Improved colors, images, and text support.

Difference between Java Swing and Java AWT


There are certain points from which Java Swing is different than Java AWT as mentioned below:
Java AWT Java Swing

Swing is a part of Java


Java AWT is an API to develop
Foundation Classes and is used
GUI applications in Java.
to create various applications.

Components of AWT are heavy The components of Java Swing


Java AWT Java Swing

weighted. are lightweight.

Components are platform Components are platform


dependent. independent.

Execution Time is more than


Execution Time is less than AWT.
Swing.

AWT components require Swing components requires


java.awt package. javax.swing package.

Swing Classes Hierarchy

Example
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JButton in JFrame Example");
JButton button = new JButton("Click Here");
button.setBounds(50, 100, 95, 30); // Set button position and size
frame.add(button); // Add the button to the frame
frame.setSize(400, 400); // Set frame size
frame.setLayout(null); // Use null layout (for demonstration purposes)
frame.setVisible(true); // Make the frame visible
}
}
output

Example2
import javax.swing.*;
public class ButtonExample extends JFrame{
ButtonExample()
{

JButton button = new JButton("Click Here");


add(button); // Add the button to the frame
setSize(300, 300); // Set frame size
setVisible(true); // Make the frame visible
}
public static void main(String[] args) {
new ButtonExample();
}
}
Output
Example1: Swing Program to add two numbers

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingAddition {
public static void main(String args[]) {
Abc obj = new Abc();
}
}
class Abc extends JFrame implements ActionListener {
JLabel l1;
JTextField t1;
JLabel l2;
JTextField t2;
JButton b;
JLabel l3;
public Abc() {
setLayout(new FlowLayout());
l1 = new JLabel("First Number:");
t1 = new JTextField(20);//20 means 20 colums will be created to fit the content on text filed
l2 = new JLabel("Second Number:");
t2 = new JTextField(20);
b = new JButton("Add");
l3 = new JLabel("Result");
add(l1);
add(t1);
add(l2);
add(t2);
add(b);
add(l3);
b.addActionListener(this);
setVisible(true);
setSize(250, 400);
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae) {
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
int value = num1 + num2;
l3.setText("" + value);
}
}
Output

Example2: Swing Program to add and subtract two numbers

import javax.swing.*;
import java.awt.event.*;
class TextFieldExample1 implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample1(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args)
{
new TextFieldExample1();
}
}
Output
Stream
A stream in Java is a sequence of objects that supports various methods which can be pipelined to produce the desired result. One
of the major new features in Java 8 is the introduction of the stream functionality – java.util.stream – which contains classes for processing
sequences of elements.

All of us have watched online videos on YouTube. When we start watching a video, a small portion of the video file is first
loaded into our computer and starts playing. we don’t need to download the complete video before we start watching it.
This is called video streaming. At a very high level, we can think of the small portions of the video file as a stream and th e
whole video as a Collection.

At the granular level, the difference between a Collection and a Stream is when the things are computed. A Collection is an
in-memory data structure that holds all the data structure’s values. Every element in the Collection has to be computed
before it can be added to the Collection. While a Stream is conceptually a pipeline in which elements are computed on
demand.

Syntax

Stream<T> stream;

Creating Streams
Streams can be created from different element sources e.g. collections or arrays with the help of stream() and of() methods:

1. Stream.of()

import java.util.stream.Stream;
import java.util.*;
public class StreamCreationEx
{
// main method
public static void main(String argvs[])
{
Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9);
stream.forEach(p -> System.out.println(p));
}
} output
1
2
3
4
5
6
7
8
9

2 Stream.of(array)

import java.util.stream.Stream;
import java.util.*;
public class StreamCreationEx
{
// main method
public static void main(String argvs[])
{
Stream<Integer> stream = Stream.of( new Integer[]{1,2,3,4,5,6,7,8,9} );
stream.forEach(p -> System.out.println(p));
}
}
Output
1
2
3
4
5
6
7
8
9

3. List.stream()
import java.util.stream.Stream;
import java.util.*;
public class StreamCreationEx
{
// main method
public static void main(String argvs[])
{
List<Integer> list = new ArrayList<Integer>();

for(int i = 1; i< 10; i++){


list.add(i);
}

Stream<Integer> stream = list.stream();


stream.forEach(p -> System.out.println(p));
}
}

4. Stream.generate()

import java.util.stream.Stream;
import java.util.*;
public class StreamCreationEx
{
// main method
public static void main(String argvs[])
{
Stream<Integer> randomNumbers = Stream
.generate(() -> (new Random()).nextInt(100));

randomNumbers.limit(10).forEach(System.out::println);
}
}
output will be of 10 randum numbers upto 100

5. Stream of String chars or tokens

import java.util.stream.Stream;
import java.util.*;
public class StreamCreationEx
{
// main method
public static void main(String argvs[])
{
Stream<String> stream2 = Stream.of("A$B$C".split("\\$"));
stream2.forEach(p -> System.out.println(p));
}
}
Output
A
B
C

Stream Operations

1 Intermediate Operations

Intermediate operations return the stream itself so you can chain multiple methods calls in a row. Let’s learn important ones.
Stream.filter()

import java.util.*;
public class StreamCreationEx
{
public static void main(String[] args){
List<String> animals_list = new ArrayList<>();
// Add elements
animals_list.add("Dog");
animals_list.add("Cat");
animals_list.add("Horse");
animals_list.add("Hen");
animals_list.add("Camel");

animals_list.stream().filter((s) -> s.startsWith("H"))


.forEach(System.out::println);
}
}
Output
Horse
Hen

Stream.sorted()

import java.util.*;
public class StreamCreationEx
{
public static void main(String[] args){
List<String> animals_list = new ArrayList<>();
// Add elements
animals_list.add("Dog");
animals_list.add("Cat");
animals_list.add("Horse");
animals_list.add("Hen");
animals_list.add("Camel");

animals_list.stream().sorted()
.map(String::toUpperCase)
.forEach(System.out::println);
}
}
Output:
CAMEL
CAT
DOG
HEN
HORSE

2. Terminal operations

Terminal operations return a result of a certain type after processing all the stream elements.
Stream.forEach()
The forEach() method helps iterate over all stream elements and perform some operation on each of
them. The operation to be performed is passed as the lambda expression.

memberNames.forEach(System.out::println);

Stream.collect()

The collect() method is used to receive elements from steam and store them in a collection.

List<String> memNamesInUppercase = memberNames.stream().sorted()

.map(String::toUpperCase)

.collect(Collectors.toList());

System.out.print(memNamesInUppercase);

Stream.count()
The count() is a terminal operation returning the number of elements in the stream as a long value.

long totalMatched = memberNames.stream()


.filter((s) -> s.startsWith("A"))
.count();

System.out.println(totalMatched);

Pipe
A pipe connects an input stream and an output stream. A piped I/O is based on the producer-consumer pattern,
where the producer produces data and the consumer consumes the data

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipeExample {

public static void main(String[] args) throws IOException {


final PipedOutputStream output = new PipedOutputStream();
final PipedInputStream input = new PipedInputStream(output);
Thread thread1 = new Thread(new Runnable() {
public void run() {
try {
output.write("Hello world, pipe!".getBytes());
} catch (IOException e) {
}
}
});
Thread thread2 = new Thread(new Runnable() {
public void run() {
try {
int data = input.read();
System.out.print("From, pipe!");
while(data != -1){
System.out.print((char) data);
data = input.read();
}
} catch (IOException e) {
}
}
});

thread1.start();
thread2.start();

}
}

File I/O
Java I/O stream is the flow of data that you can either read from, or you can write to.It is used to perform read and write operations in file
permanently. Java uses streams to perform these tasks. Java I/O stream is also called File Handling, or File I/O. It is available
in java.io package.
Java.io package provides classes for system input and output through files, network streams, memory buffers, etc.

Streams are the sequence of bits(data).


There are two types of streams:

 Input Streams
 Output Streams

Input Streams:
Input streams are used to read the data from various input devices like keyboard, file, network, etc.
Output Streams:
Output streams are used to write the data to various output devices like monitor, file, network, etc.
Example: To Read
import java.io.FileInputStream;
public class FileRead {
public static void main(String args[]) {
try {
FileInputStream input = new FileInputStream("F://MyFile.txt");
System.out.println("Data in the file: ");
// Reads the first byte
int i = input.read();
while(i != -1) {
System.out.print((char)i);
// Reads next byte from the file
i = input.read();
}
input.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
Output:
Data in the file:
hari mohan

Example: To Write
import java.io.FileOutputStream;
public class FileWrite {
public static void main(String[] args) {
String data = "JECRC University";
try {
FileOutputStream output = new FileOutputStream("F://ff.txt");
byte[] array = data.getBytes();
// Writes byte to the file
output.write(array);
output.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
output

Java File
The File class of the java.io package is used to perform various operations on files and directories.

Example:CreateFile
import java.io.File;
import java.io.File;
class CreateFile {
public static void main(String[] args) {
File file = new File("f://fff.txt");
try {
boolean value = file.createNewFile();
if (value) {
System.out.println("The new file is created.");
System.out.println("File name :" + file.getName());
System.out.println("Path: " + file.getPath());

}
else {
System.out.println("The file already exists.");
}
}
catch(Exception e) {
e.getStackTrace();
}
}
}
Output
The new file is created.
File name :fff.txt
Path: f:\fff.txt

Path
java.nio.file.Paths class contains static methods for converting path string into Path.
Example
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathClass {
public static void main(String[] args)
throws IOException
{
Path path = (Path)Paths.get("/usr", "local", "bin");
System.out.println(path);
}
}
Output
\usr\local\bin

You might also like