Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 18

Web Technologies

UNIT 2- JAVA GUI, FILE STREAM AND CONCURRENCY


GUI Development using SWING – I/O Streams and Object Serialization – Generic
Collections – Concurrency – Thread States and Life Cycles – Thread Synchronization –
Java Networking
Java Inner Class
• Java inner class or nested class is a class that is declared inside the class or interface.
• Use inner classes to logically group classes and interfaces in one place to be more readable and maintainable.
• Additionally, it can access all the members of the outer class, including private data members and methods.
Syntax: class Java_Outer_class{
//code
class Java_Inner_class{
//code } }
Advantages of inner classes :
Nested classes represent a particular type of relationship that is it can access all the members (data members and methods)
of the outer class, including private.
Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in
one place only.
Code Optimization: It requires less code to write.
An inner class is a part of a nested class. Non-static nested classes are known as inner classes.
• Two types of nested classes non-static and static nested classes. The non-static nested classes are also known as inner
classes.
• Non-static nested class (inner class)
• Member inner class-A class created within class and outside method.
• Anonymous inner class-A class created for implementing an interface or extending class. The java compiler decides its name.
• Local inner class-A class was created within the method.
• Static nested class-A static class was created within the class.
Java Inner Class
public class TestMemberOuter{ Anonymous inner class
private int data=30;
class Inner{ A class that has no name is known as an anonymous
void msg(){System.out.println("data is "+data);} inner class in Java.
}
It should be used if you have to override a method of
public static void main(String args[]){
TestMemberOuter obj=new TestMemberOuter(); class or interface. Java
TestMemberOuter.Inner in=obj.new Inner();
in.msg(); Anonymous inner class can be created in two ways:
} } Class (may be abstract or concrete).
Interface
An object or instance of a member's inner class always exists
within an object of its outer class.

The new operator is used to create the object of member inner


class with slightly different syntax.

OuterClassReference.new MemberInnerClassConstructor();
The java compiler creates two class files in the case of the inner
class.
The class file name of the inner class is "Outer$Inner". If you want
to instantiate the inner class, you must have to create the instance
of the outer class.
In such a case, an instance of inner class is created inside the
instance of the outer class.
Java Inner Class
Normal : Anonymous inner class

class a{ class a{
public void show() public void show() {
{ System.out.println("In Class A"); System.out.println("In Class A");
}} }}
class b extends a{ public class anoneg{
public void show() public static void main(String a[]) {
{ System.out.println("In Class B"); a obj= new a(){
}} public void show()
public class anoneg{ { System.out.println("In Class
public static void main(String a[]) { B"); } }; obj.show();
a obj= new b(); }}
obj.show();
}}
Java Inner Class
Normal : Anonymous inner class

interface abc interface abc


{ {
void show(); void show();
} }
class implementor implements abc
{ public class ifdemo
public void show() {
{ public static void main(String a[])
System.out.println("anything"); {
} abc obj=new abc()
} {
public class ifdemo public void show()
{ {
public static void main(String a[]) System.out.println("Welcome");
{ }
abc obj=new implementor(); };
obj.show(); obj.show();
} }
} }
Java AWT and Swing
• AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or windows-
based applications in Java.
• Java AWT components are platform-dependent i.e. components are displayed according to the view
of operating system.
• AWT is heavy weight i.e. its components are using the resources of underlying operating system
(OS).
• java.awt package provides classes for AWT API such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List etc.
• 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.
Java AWT & Swing

S.NO AWT Swing

Swing is a part of Java Foundation Classes and is used to


1. Java AWT is an API to develop GUI applications in Java create various applications.

2. The components of Java AWT are heavy weighted. The components of Java Swing are light weighted.

3. Java AWT has comparatively less functionality as Java Swing has more functionality as compared to AWT.
compared to Swing.

4. The execution time of AWT is more than Swing. The execution time of Swing is less than AWT.

5. The components of Java AWT are platform dependent. The components of Java Swing are platform independent.

6. MVC pattern is not supported by AWT. MVC pattern is supported by Swing.

7. AWT provides comparatively less powerful Swing provides more powerful components.
components.
Java Swing
• Java Foundation Classes (JFC) are a set of GUI
components which simplify the development of
desktop applications.

Methods of Component class are widely used in java


swing

• public void add(Component c)add a component


on another component.
• public void setSize(int width,int height)sets size
of the component.
• public void setLayout(LayoutManager m)sets the
layout manager for the component.
• public void setVisible(boolean b)sets the visibility
of the component. It is by default false.
Java Swing
import javax.swing.*;
Two ways to create a frame: public class sample {
• By creating the object of Frame class (association) JFrame f;
sample(){
• By extending Frame class (inheritance) f=new JFrame();//creating instance of JFrame
Creating one button and adding it on the JFrame object JButton b=new JButton("click");//creating instance of JButton
inside the main() method. b.setBounds(130,100,100, 40);
import javax.swing.*;
f.add(b);//adding button in JFrame
public class sample {
public static void main(String[] args) { f.setSize(400,500);//400 width and 500 height
JFrame f=new JFrame();//creating instance of JFrame f.setLayout(null);//using no layout managers
JButton b=new JButton("click");// f.setVisible(true);//making the frame visible
creating instance of JButton }

b.setBounds(130,100,100, 40);//x axis, y axis, width, height public static void main(String[] args) {
f.add(b);//adding button in JFrame new sample();
f.setSize(400,500);//400 width and 500 height }
}
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
Java Swing Commonly used controls while designing GUI using SWING.
JlabelA JLabel object is a component for placing text in a container.
JbuttonThis class creates a labeled button.
import javax.swing.*; JColorChooserA JColorChooser provides a pane of controls designed to allow
public class sample extends JFrame{//inheriting JFrame a user to manipulate and select a color.
JCheck BoxA JCheckBox is a graphical component that can be in either an on
JFrame f; (true) or off (false) state.
sample(){ JRadioButtonThe JRadioButton class is a graphical component that can be in
either an on (true) or off (false) state. in a group.
JButton b=new JButton("click");//create button JlistA JList component presents the user with a scrolling list of text items.
b.setBounds(130,100,100, 40); JComboBoxA JComboBox component presents the user with a to show up
menu of choices.
add(b);//adding button on frame JTextFieldA JTextField object is a text component that allows for the editing
setSize(400,500); of a single line of text.
JPasswordFieldA JPasswordField object is a text component specialized for
setLayout(null); password entry.
setVisible(true); JTextAreaA JTextArea object is a text component that allows editing of a
multiple lines of text.
} ImageIconA ImageIcon control is an implementation of the Icon interface
that paints Icons from Images
public static void main(String[] args) {
JscrollbarA Scrollbar control represents a scroll bar component in order to
new sample(); enable the user to select from range of values.
JFileChooserA JFileChooser control represents a dialog window from which
}} the user can select a file.
JProgressBarAs the task progresses towards completion, the progress bar
displays the task's percentage of completion.
JsliderA JSlider lets the user graphically select a value by sliding a knob
within a bounded interval.
Java Swing
User interface considers the following three main
aspects − Foreground Events − These events require direct interaction of the
user.
• UI Elements − These are the core visual
They are generated as consequences of a person interacting with the
elements the user eventually sees and interacts graphical components in the Graphical User Interface.
with.
• Layouts − They define how UI elements should Background Events − These events require the interaction of the end
be organized on the screen and provide a final user.
look and feel to the GUI (Graphical User Eg., Operating system interrupts, hardware or software failure, timer
Interface). expiration, and operation completion are some examples of
• Behavior − These are the events which occur background events.
when the user interacts with UI elements.
Event Handling is the mechanism that controls the event and decides
Change in the state of an object is known as what should happen if an event occurs.
Event, i.e., event describes the change in the This mechanism has a code which is known as an event handler, that
state of the source. is executed when an event occurs.
Events are generated as a result of user Java uses the Delegation Event Model to handle the events. This
interaction with the graphical user interface model defines the standard mechanism to generate and handle the
components. events.
Eg., clicking on a button, moving the mouse,
entering a character through keyboard, selecting
an item from the list
Java Swing
The Delegation Event Model has the following key participants.
Steps Involved in Event Handling
Step 1 − The user clicks the button and the event is generated.
Source − The source is an object on which the event occurs.
Step 2 − The object of concerned event class is created automatically
• Source is responsible for providing information of the and information about the source and the event get populated within
occurred event to it's handler. Java provide us with classes for
the source object. the same object.
Step 3 − Event object is forwarded to the method of the registered
Listener − event handler.
listener class.
• The listener is responsible for generating a response to an Step 4 − The method is gets executed and returns.
event.
• By implementation, the listener is also an object. The listener
waits till it receives an event. Once the event is received, the
listener processes the event and then returns.
The benefit of this approach is that the user interface logic is
completely separated from the logic that generates the event.
The user interface element is able to delegate the processing of
an event to a separate piece of code.
In this model, the listener needs to be registered with the
source object so that the listener can receive the event
notification.
This is an efficient way of handling the event because the event
notifications are sent only to those listeners who want to
receive them.
Java Swing controlPanel = new JPanel();
import java.awt.*;
controlPanel.setLayout(new FlowLayout());
import java.awt.event.*; mainFrame.add(headerLabel);
import javax.swing.*; mainFrame.add(controlPanel);
public class sample {
private JFrame mainFrame; mainFrame.add(statusLabel);
private JLabel headerLabel; mainFrame.setVisible(true);
private JLabel statusLabel; }
private JPanel controlPanel;
private void showEventDemo(){
public sample(){ headerLabel.setText("Control in action: Button");
prepareGUI(); JButton okButton = new JButton("OK");
}
public static void main(String[] args){ JButton submitButton = new JButton("Submit");
sample swingControlDemo = new sample(); JButton cancelButton = new JButton("Cancel");
swingControlDemo.showEventDemo(); okButton.setActionCommand("OK");
}
private void prepareGUI(){ submitButton.setActionCommand("Submit");
mainFrame = new JFrame("Java SWING Examples"); cancelButton.setActionCommand("Cancel");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
headerLabel = new JLabel("",JLabel.CENTER ); cancelButton.addActionListener(new ButtonClickListener());
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100); controlPanel.add(okButton);
controlPanel.add(submitButton);
mainFrame.addWindowListener(new WindowAdapter() { controlPanel.add(cancelButton);
public void windowClosing(WindowEvent windowEvent){
System.exit(0); mainFrame.setVisible(true);
} }
});
Java Swing
private class ButtonClickListener implements
ActionListener{
public void actionPerformed(ActionEvent e)
{
String command =
e.getActionCommand();
if( command.equals( "OK" )) {
statusLabel.setText("Ok Button
clicked.");
} else if( command.equals( "Submit" ) ) {
statusLabel.setText("Submit Button
clicked.");
} else {
statusLabel.setText("Cancel Button
clicked.");
}
}
}
}
Java Swing
Displaying graphics in swing:

Methods of Graphics class:

public abstract void drawString(String str, int x, int y) is used to draw the specified string.
public void drawRect(int x, int y, int width, int height) draws a rectangle with the specified width and height.
public abstract void fillRect(int x, int y, int width, int height)is used to fill rectangle with the default color and
specified width and height.
public abstract void drawOval(int x, int y, int width, int height)is used to draw oval with the specified width
and height.
public abstract void fillOval(int x, int y, int width, int height) is used to fill oval with the default color and
specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2)is used to draw line between the points(x1, y1) and
(x2, y2).
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)is used draw the
specified image.
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)is used draw a
circular or elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)is used to fill a circular
or elliptical arc.
public abstract void setColor(Color c) is used to set the graphics current color to the specified color.
public abstract void setFont(Font font) is used to set the graphics current font to the specified font.
Java Swing
Displaying graphics in swing:

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

public class DisplayGraphics extends Canvas{

public void paint(Graphics g) {


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

g.fillArc(30, 130, 40,50,180,40);

}
public static void main(String[] args) {
DisplayGraphics m=new DisplayGraphics();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);
//f.setLayout(null);
f.setVisible(true);
}

}
Java Swing
Displaying image in swing:

use the method drawImage() of Graphics class.

Syntax of drawImage() method:


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

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

public class Mycanvas extends Canvas{

public void paint(Graphics g) {

Toolkit t=Toolkit.getDefaultToolkit();
Image i=t.getImage("E:\\java.jpg");
g.drawImage(i, 0,0,this);

}
public static void main(String[] args) {
Mycanvas m=new Mycanvas();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);
f.setVisible(true);
}

}
Java Swing
BorderLayoutThe borderlayout arranges the components to fit in
Layout Manager
the five regions: east, west, north, south, and center.
• The layout manager automatically positions all the CardLayout The CardLayout object treats each component in the
components within the container.
container as a card. Only one card is visible at a time.
• Even if you do not use the layout manager, the FlowLayoutThe FlowLayout is the default layout. It layout the
components are still positioned by the default layout
components in a directional flow.
manager.
GridLayoutThe GridLayout manages the components in the form
• It is possible to lay out the controls by hand, however, of a rectangular grid.
it becomes very difficult because of the following two
reasons. GridBagLayoutThis is the most flexible layout manager class.
The object of GridBagLayout aligns the component vertically,
It is very tedious to handle a large number of
horizontally, or along their baseline without requiring the
controls within the container.
components of the same size.
Usually, the width and height information of a GroupLayoutThe GroupLayout hierarchically groups the
component is not given when we need to arrange them.
components in order to position them in a Container.
• Java provides various layout managers to position the SpringLayoutA SpringLayout positions the children of its
controls.
associated container according to a set of constraints.
• Properties like size, shape, and arrangement varies
from one layout manager to the other.
• When the size of the applet or the application window
changes, the size, shape, and arrangement of the
components also changes in response, i.e. the layout
managers adapt to the dimensions of the appletviewer
or the application window.

You might also like