SlideShare a Scribd company logo
1 of 87
UNIT V
EVENT DRIVEN PROGRAMMING
Introducing Graphics – Working with color, font and images – Introduction to
AWT – Origins of Swing – Two Key Swing Features – MVC Connection –
Components and Containers – The Swing Packages – A Simple Swing
Application – Event handling – Creating a Swing Applet – Exploring Swing :
JLabel, ImageIcon, JTextField, The Swing Buttons, JScrollPane, JList and
JComboBox – Creating Menus.
1
Introducing Graphics
• The java.awt.Graphics class provides many methods for graphics
programming.
• A graphics context is encapsulated by the Graphics class and is
obtained in two ways:
• It is passed to an applet when one of its various methods, such as
paint( ) or update( ) is called.
• It is returned by the getGraphics( ) method of Component.
2
Graphics Methods
Method Description
abstract Graphics create() Creates a new Graphics object that is a copy
ofthis Graphics object
abstract void drawString(String str, int x, int y) Draws the text given by the specified string
void drawRect(int x, int y, int width, int height) draws a rectangle with the specified width and
height
void draw3DRect(int x, int y, int width, int height,
boolean raised)
Draws a 3-D highlighted outline of the specified
rectangle.
abstract void drawRoundRect(int x, int y, int
width, int height, int arcWidth, int arcHeight)
Draws an outlined round-cornered rectangle
using this graphics context's current color
abstract void fillRect(int x, int y, int width, int
height)
fill rectangle with the default color and specified
width and height.
3
Method Description
abstract void drawPolygon(int[] xPoints, int[]
yPoints, int nPoints)
Draws a closed polygon defined by arrays of x
and y coordinates.
abstract void fillPolygon(int[] xPoints, int[]
yPoints, int nPoints)
Fills a closed polygon defined by arrays of x
and y coordinates.
abstract void drawOval(int x, int y, int width,
int height)
draw oval with the specified width and height.
abstract void fillArc(int x, int y, int width, int height,
int startAngle, int arcAngle)
fill a circular or elliptical arc.
abstract void setColor(Color c) set the graphics current color to the specified color.
abstract void setFont(Font font) set the graphics current font to the specified font.
4
Example:
import java.applet.Applet;
import java.awt.*;
public class Graphics1 extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
<html>
<body>
<applet code="Graphics1.class" width="300" height="300">
</applet>
</body>
</html>
5
6
UNIT V
EVENT DRIVEN PROGRAMMING
Introducing Graphics – Working with color, font and images – Introduction to
AWT – Origins of Swing – Two Key Swing Features – MVC Connection –
Components and Containers – The Swing Packages – A Simple Swing
Application – Event handling – Creating a Swing Applet – Exploring Swing :
JLabel, ImageIcon, JTextField, The Swing Buttons, JScrollPane, JList and
JComboBox – Creating Menus.
7
Working with color, font and images
• To support different colors Java package comes with the Color class.
The Color class states colors in the default RGB color space or colors
in arbitrary color spaces identified by a ColorSpace.
• Color class static color variable available are:
8
• Color.black
• Color.lightGray
• Color.blue
• Color.magenta
• Color.cyan
• Color.orange
• Color.darkGray
• Color.pink
• Color.gray
• Color.red
• Color.green
• Color.white
• Color.yellow
9
Color class constructor
• Color(float r, float g, float b) – create color with specified red, green,
and blue values in the range (0.0 - 1.0)
• Color(int r, int g, int b)- create color with the specified red, green, and
blue values in the range (0 - 255).
Method Description
int getRed() Returns the red component in the range 0-255
in the default sRGB space.
int getGreen() Returns the green component in the range 0-
255 in the default sRGB space
int getBlue() Returns the blue component in the range 0-255
in the default sRGB space.
Color getHSBColor(float h, float s, float b) Creates a Color object based on the specified
values for the HSB color model.
10
Fonts in Java & Font class constructor
• The Font class states fonts, which are used to render text in a visible
way.
• Font(Fontfont) //Creates a new Font from the specifiedfont.
• Font(String name, int style,intsize) //Creates a new Font from the
specified name, style and pointsize
11
12
import java.awt.*;
import java.applet.*;
public class colo extends Applet
{
Font f1,f2,f3;
public void init()
{
f1 = new Font("Arial",Font.BOLD,18);
f2 = new Font("Forte",Font.PLAIN,24);
f3 = new Font("Elephant",Font.ITALIC,28)
;
}
public void paint(Graphics g)
{
setBackground(Color.yellow);
g.setColor(Color.red);
g.drawString(“Kongunadu",50,50);
g.setColor(Color.blue);
g.setFont(f1);
g.drawString(“CSE",50,80);
g.setColor(Color.green);
g.setFont(f2);
g.drawString(“Second Year",50,110);
g.setColor(Color.magenta);
g.setFont(f3);
g.drawString(“Welcome",50,140);
}
}
13
14
Images in Java
• Image control is superclass for all image classes representing graphical
images.
Image class constructor
Image()// create an Image object
15
import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),“kongu.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}
<html>
<body>
<applet code="DisplayImage.class" width="300" height="300">
</applet>
</body>
</html>
16
UNIT V
EVENT DRIVEN PROGRAMMING
Introducing Graphics – Working with color, font and images – Introduction to
AWT – Origins of Swing – Two Key Swing Features – MVC Connection –
Components and Containers – The Swing Packages – A Simple Swing
Application – Event handling – Creating a Swing Applet – Exploring Swing :
JLabel, ImageIcon, JTextField, The Swing Buttons, JScrollPane, JList and
JComboBox – Creating Menus.
17
Introduction to AWT
• The Abstract Window Toolkit (AWT) is Java's original platform-
independent windowing, graphics, and user-interface widget
toolkit. The AWT classes are contained in the java.awt package.
• Contains all of the classes for creating user interfaces and for
painting graphics and images.
• An API to develop GUI or window-based applications in java.
18
19
• Component
A component is an object having a graphical representation that can
be displayed on the screen and that can interact with the user.
Examples : buttons, checkboxes, and scrollbars
• Container
The Container class is the subclass of Component. The container object
is a component that can contain other AWT components.
• Window
The class Window is a top level window with no border and no
menubar. The default layout for a window is BorderLayout. A window
must have either a frame, dialog, or another window defined as its
owner when it's constructed.
20
• Panel
It provides space in which an application can attach any other component,
including other panels. The default layout manager for a panel is the
FlowLayout layout manager
• Frame
A Frame is a top-level window with a title and a border. It uses
BorderLayout as default layout manager.
• Dialog
A Dialog is a top-level window with a title and a border that is typically
used to take some form of input from the user.
• Canvas
A Canvas component represents a blank rectangular area of the screen onto
which the application can draw or from which the application can trap
input events from the user. The paint method must be overridden in order
to perform custom graphics on the canvas. It is not a part of hierarchy of
JavaAWT.
21
• Frame Constructor
Frame() Constructs a new instance of Frame that is initially invisible.
Frame(String)
22
23
Creating a Frame
• We can generate a window by creating an instance of Frame.
• The created frame can be made visible by calling setVisible( ).
• When created, the window is given a default height and width. The
size of the window can be changed explicitly by calling the setSize( )
method.
• A label can be added to the current frame by creating an Label
instance and calling the add() method.
24
import java.awt.*;
public class AwtFrame1{
public static void main(String[] args){
Frame frm = new Frame("Java AWT Frame");
Label lbl = new Label("Kongunadu College of Engg.&
Tech.",Label.CENTER);
frm.add(lbl);
frm.setSize(400,400);
frm.setVisible(true);
}
}
25
UNIT V
EVENT DRIVEN PROGRAMMING
Introducing Graphics – Working with color, font and images – Introduction to
AWT – Origins of Swing – Two Key Swing Features – MVC Connection –
Components and Containers – The Swing Packages – A Simple Swing
Application – Event handling – Creating a Swing Applet – Exploring Swing :
JLabel, ImageIcon, JTextField, The Swing Buttons, JScrollPane, JList and
JComboBox – Creating Menus.
26
MVC
• Model designs based on MVC
architecture follow the MVC
design pattern and they separate
the application logic from the user
interface when designing software.
As the name implies MVC pattern
has three layers, which are:
• Model – Represents the business
layer of the application
• View – Defines the presentation of
the application
• Controller – Manages the flow of
the application
27
Implementation of MVC using Java
• To implement a web application based on MVC design pattern, we
will create
• Employee Class, which acts as the model layer
• Employee View Class, which defines the presentation layer (view layer)
• Employee Controller Class, which acts as a controller
28
The Model Layer
• In the MVC design pattern, the model is the data layer which defines
the business logic of the system and also represents the state of the
application.
• The model objects retrieve and store the state of the model in a
database Now, let’s create a model using Employee Class.
29
public class Employee {
// declaring the variables
private String EmployeeName;
private String EmployeeId;
private String EmployeeDepartment;
// defining getter and setter methods
public String getId() {
return EmployeeId;
}
public void setId(String id) {
this.EmployeeId = id;
}
public String getName() {
return EmployeeName;
}
public void setName(String name) {
this.EmployeeName = name;
}
public String getDepartment() {
return EmployeeDepartment;
}
public void setDepartment(String Department) {
this.EmployeeDepartment = Department;
}
}
The Model Layer
30
The View Layer
// class which represents the view
public class EmployeeView {
// method to display the Employee details
public void printEmployeeDetails (String EmployeeName, String EmployeeId, String EmployeeDepartment)
{
System.out.println("Employee Details: ");
System.out.println("Name: " + EmployeeName);
System.out.println("Employee ID: " + EmployeeId);
System.out.println("Employee Department: " + EmployeeDepartment);
}
}
31
The Controller Layer
public class EmployeeController {
private Employee model;
private EmployeeView view;
// constructor to initialize
public EmployeeController(Employee model, EmployeeVi
ew view) {
this.model = model;
this.view = view;
}
// getter and setter methods
public void setEmployeeName(String name){
model.setName(name);
}
public String getEmployeeName(){
return model.getName();
}
}
public void setEmployeeId(String id){
model.setId(id);
}
public String getEmployeeId(){
return model.getId();
}
public void setEmployeeDepartment(String Departm
{
model.setDepartment(Department);
}
public String getEmployeeDepartment(){
return model.getDepartment();
}
// method to update view
public void updateView() {
view.printEmployeeDetails(model.getName(), model.g
), model.getDepartment());
} 32
Main Class Java file
public class MVCMain {
public static void main(String[] args) {
// fetching the employee record based on the employee_id from the
database
Employee model = retriveEmployeeFromDatabase();
// creating a view to write Employee details on console
EmployeeView view = new EmployeeView();
EmployeeController controller = new EmployeeController(mode
l, view);
controller.updateView();
//updating the model data
controller.setEmployeeName("Nirnay");
System.out.println("n Employee Details after updating: ");
controller.updateView();
}
private static Employee retriveEmployeeFromDatabase
Employee Employee = new Employee();
Employee.setName("Anu");
Employee.setId("11");
Employee.setDepartment("Salesforce");
return Employee;
}
}
33
Output
Employee Details:
Name: Anu
Employee ID: 11
Employee Department: Salesforce
Employee Details after updating:
Name: Nirnay
Employee ID: 11
Employee Department: Salesforce
34
UNIT V
EVENT DRIVEN PROGRAMMING
Introducing Graphics – Working with color, font and images – Introduction to
AWT – Origins of Swing – Two Key Swing Features – MVC Connection –
Components and Containers – The Swing Packages – A Simple Swing
Application – Event handling – Creating a Swing Applet – Exploring Swing :
JLabel, ImageIcon, JTextField, The Swing Buttons, JScrollPane, JList and
JComboBox – Creating Menus.
35
Components and Containers
• In Java, a component is the basic user interface object and is found in
all Java applications. Components include lists, buttons, panels, and
windows.
• Swing provides the following useful top-level containers, all of which
inherit from JComponent:
36
JWindow
• JWindow is a top-level window
that doesn't have any trimmings
and can be displayed anywhere
on a desktop.
• JWindow is a heavyweight
component. You usually use
JWindow to create pop-up
windows and "splash" screens.
JWindow extends AWT's
Window class.
37
JFrame
• JFrame is a top-level window
that can contain borders and
menu bars. JFrame is a subclass
of JWindow and is thus a
heavyweight component.
JDialog
• JDialog is a lightweight
component that you use to
create dialog windows. You can
place dialog windows on a
JFrame or JApplet. JDialog
extends AWT's Dialog class.
38
JApplet
• JApplet is a container that
provides the basis for applets
that run within web browsers.
JApplet is a lightweight
component that can contain
other graphical user interface
(GUI) components. JApplet
extends AWT's Applet class.
39
• All Swing components - including the JApplet and JDialog containers -
need to be contained at some level inside a JWindow or JFrame.
40
• Each top-level container consists
of the following panes:
Root pane
• The root pane is an intermediate
container that manages the
layered pane, content pane, and
glass pane.
• It can also manage an optional
menu bar.
41
Layered pane
• The layered pane contains the
content pane and the optional
menu bar. It can also contain
other components, which it
arranges so that they overlap
each other.
Content pane
• It covers the visible section of
the JFrame or JWindow and you
use it to add components to the
display area..
42
UNIT V
EVENT DRIVEN PROGRAMMING
Introducing Graphics – Working with color, font and images – Introduction to
AWT – Origins of Swing – Two Key Swing Features – MVC Connection –
Components and Containers – The Swing Packages – A Simple Swing
Application – Event handling – Creating a Swing Applet – Exploring Swing :
JLabel, ImageIcon, JTextField, The Swing Buttons, JScrollPane, JList and
JComboBox – Creating Menus.
43
Event handling
• Any change in the state of any object is called event.
• For Example: Pressing a button, entering a character in Textbox,
Clicking or dragging a mouse, etc.
• The three main components in event handling are:
• Events
• Events Source
• Listeners
44
• Events: An event is a change in state of an object. For example,
mouseClicked,mousePressed.
• Events Source: Event source is an object that generates an event.
Example: a button, frame, textfield.
• Listeners: A listener is an object that listens to the event. A listener
gets notified when an event occurs. When listener receives an event,
it process it and then return.
• Listeners are group of interfaces and are defined in java.awt.event package.
Each component has its own listener. For example MouseListener handles
allMouseEvent
45
46
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends
Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
47
48
UNIT V
EVENT DRIVEN PROGRAMMING
Introducing Graphics – Working with color, font and images – Introduction to
AWT – Origins of Swing – Two Key Swing Features – MVC Connection –
Components and Containers – The Swing Packages – A Simple Swing
Application – Event handling – Creating a Swing Applet – Exploring Swing :
JLabel, ImageIcon, JTextField, The Swing Buttons, JScrollPane, JList and
JComboBox – Creating Menus.
49
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.
50
Swing Features
• Light Weight -
• Rich controls -like Tree, TabbedPane, slider, colourpicker,
tablecontrols
• Highly Customizable - controls can be customized in very easy way
as visual appearance.
• Pluggable look-and-feel- SWING based GUI Application look and feel
can be changed at run time based on available values.
51
52
The following program is an example for Java
Swing.
import javax.swing.*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click"); //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
}
} 53
The following program is an example for Java
Swing.
import javax.swing.*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();
JButton b=new JButton("click");
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);
f.setVisible(true);
}
} 54
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;
public class SwingExample3 implements Runnable
{
public void run()
{
JFrame f = new JFrame("Swingexample");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
;
f.setLayout(new FlowLayout());
f.add(new JLabel("JAVA PROGRAMMING!"));
f.add(new JButton("OK"));
f.pack();
f.setVisible(true);
}
public static void main(String[] args)
{
SwingExample3 se = new SwingExample3();
SwingUtilities.invokeLater(se);
}
}
55
Layout management
• Java LayoutManagers
• The LayoutManagers are used to
arrange components in a
particular manner.
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayoutetc.
56
Java BorderLayout
• The BorderLayout is used to
arrange the components in five
regions: north, south, east, west
and center.
• Each region (area) may contain one
component only. It is the default
layout of frame or window.
• 1. public static final intNORTH
• 2. public static final intSOUTH
• 3. public static final intEAST
• 4. public static final intWEST
• 5. public static final intCENTER
57
Java 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
arow.
2. GridLayout(int rows, int columns): creates a grid layout with the given
rows and columns but no gaps between thecomponents.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid
layout with the given rows and columns alongwith given horizontal and
verticalgaps.
58
import java.awt.*;
import javax.swing.*;
public class GridE2
{
JFrame f;
GridE2()
{
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");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.setLayout(new GridLayout(2,4));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
}
public static void main(String[] args)
{
new GridE2();
} 59
60
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.
• Fields of FlowLayout class
1. public static final intLEFT
2. public static final intRIGHT
3. public static final int CENTER
4. public static final intLEADING
5. public static final intTRAILING
61
Constructors of FlowLayoutclass
• 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 verticalgap.
• 3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with
the given alignment and the given horizontal and verticalgap.
62
import java.awt.*;
import javax.swing.*;
public class FlowE1{
JFrame f;
FlowE1()
{ 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.LEFT));
//setting flow layout of left alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{ new FlowE1();
}
}
63
Java BoxLayout
• The BoxLayout is used to arrange the components either vertically or
horizontally. For this purpose, BoxLayout provides four constants.
They are as follows:
• Fields of BoxLayout class
1. public static final intX_AXIS
2. public static final intY_AXIS
3. public static final intLINE_AXIS
4. public static final intPAGE_AXIS
64
65
Java GridBagLayout
• The Java GridBagLayout class is used to align components vertically,
horizontally or along their baseline. The components may not be of
same size. Each GridBagLayout object maintains a dynamic,
rectangular grid of cells.
66
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame
{
public static void main(String[] args)
{
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample()
{
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy =0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy =0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx =0;
gbc.gridy =1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy =1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy =2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE); }
}
67
68
Java SpringLayout
• A SpringLayout arranges the children of its associated container
according to a set of constraints. Constraints are nothing but
horizontal and vertical distance between two component edges.
Every constrains are represented by a SpringLayout.Constraint object.
69
Swing Components
• The Swing components Text Fields, Text Areas and Buttons are
explained.
70
• Swing Components and Containers
• A component is an independent visual control. Swing Framework
contains a large set of components which provide rich functionalities
and allow high level of customization.
• They all are derived from JComponent class. All these components
are lightweight components.
• This class provides some common functionality like pluggable look
and feel, support for accessibility, drag and drop, layout, etc.
• A container holds a group of components. It provides a space where a
component can be managed and displayed. Containers are of two
types:
• 1. Top level Containers
• 2. LightweightContainers
71
72
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
public class TextAreaE1
{
public static void main(String[] args)
{
JFrame f = new JFrame("Text Area Examples");
JPanel upperPanel = new JPanel();
JPanel lowerPanel = new JPanel();
f.getContentPane().add(upperPanel, "North");
f.getContentPane().add(lowerPanel, "South");
upperPanel.add(new JTextArea(content));
upperPanel.add(new JTextArea(content, 6, 10));
upperPanel.add(new JTextArea(content, 3, 8));
lowerPanel.add(new JScrollPane(new JTextArea(content, 6, 8)));
JTextArea ta = new JTextArea(content, 6, 8);
ta.setLineWrap(true);
lowerPanel.add(new JScrollPane(ta));
ta = new JTextArea(content, 6, 8);
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
lowerPanel.add(new JScrollPane(ta));
f.pack();
f.setVisible(true);
}
static String content = "JAVA PROGRAMMING";
}
73
74
TextField
• JTextField is used for taking input of single line of text. It is most
widely used text component. It has three constructors,
• JTextField(intcols)
• JTextField(String str, intcols)
• JTextField(Stringstr)
75
import java.awt.event.*;
import java.awt.*;
public class TextFieldE1 extends JFrame
{
public TextFieldE1()
{
JTextField jtf =newJTextField(20); //creating
JTextField.
add(jtf); //adding JTextField to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
setVisible(true);
}
public static void main(String[] args)
{
new TextFieldE1();
}
}
76
Button:
• JButton class provides functionality of a button. JButton class has
three constructors. JButton(Iconic) JButton(Stringstr)
JButton(String str, Iconic)
• It allows a button to be created using icon, a string or both. JButton
supports ActionEvent. When a button is pressed an ActionEvent is
generated.
77
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class testbutton extends JFrame
{
testbutton()
{
JButton bt1 = new JButton("OK");
JButton bt2 = new JButton("NOt OK");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting close operation.
setLayout(newFlowLayout()); //setting layout using FlowLayout object
setSize(400,400); //setting size ofJframe
add(bt1); //adding Yes button toframe.
add(bt2); //adding No button toframe.
setVisible(true);
}
public static void main(String[] args)
{
new testbutton();
}
}
78
JCheckBox
• JCheckBox class is used to create checkboxes inframe.
• It is used to turn an option on (true) or off (false). Clicking on a
CheckBox changes its state from "on" to "off" or from "off" to "on".
• It inherits JToggleButtonclass.
79
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{{
JCheckBox jcb = new JCheckBox("Correct"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb =newJCheckBox("Wrong"); //creating JCheckBox.
add(jcb); //adding JCheckBox toframe.
jcb =newJCheckBox("Maybe"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args) {
new Test();
}
}
80
JRadioButton
• JRadioButton class is used to create a radio button in Frames.
• It is used to choose one option from multipleoptions.
• It is widely used in exam systems or quiz.
• It should be added in ButtonGroup to select one radio button only
81
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame {
public Test()
{
JRadioButton jcb =newJRadioButton("Male");
add(jcb);
jcb =newJRadioButton("Female");
add(jcb); //
jcb = newJRadioButton("Transgender");
add(jcb);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true); }
public static void main(String[] args)
{
new Test();
}
}
82
Java JList
• The object of JList class represents a list of textitems.
• The list of text items can be set up so that the user can choose either
one item or multipleitems.
• It inherits JComponentclass.
83
import javax.swing.*;
public class Test22
{ Test()
{
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("CSE");
l1.addElement("IT");
l1.addElement("ECE");
l1.addElement("EEE");
l1.addElement("CIVIL");
l1.addElement("MECHANICAL");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(900,900);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]) {
new Test22();
}
} 84
Java JMenuBar, JMenu and JMenuItem
Creating Menus
• The JMenuBar class is used to display menubar on the window or frame. It
may have several menus.
• The Menu class represents the pull-down menu component which is
deployed from a menubar.
• A JMenu is a container that can hold menu items that represent
theoptions.
• The object of JMenu class is a pull down menu component which is
displayed from the menu bar. It inherits the JMenuItemclass.
• The object of JMenuItem class adds a simple labeled menu item. The items
used in a menu must belong to the JMenuItem or any of itssubclass.
85
import javax.swing.*;
public class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5, i6, i7;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("File Menu");
submenu=new JMenu("Print");
i1=new JMenuItem("New");
i2=new JMenuItem("Open");
i3=new JMenuItem("Save");
i4=new JMenuItem("Save As");
i5=new JMenuItem("Print");
i6=new JMenuItem("Quick Print");
i7=new JMenuItem("Print Preview");
menu.add(i1);
menu.add(i2);
menu.add(i3);
menu.add(i4);
submenu.add(i5);
submenu.add(i6);
submenu.add(i7);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample(); }
} 86
87

More Related Content

Similar to U5 JAVA.pptx

Displaying information within a window.68
Displaying information within a window.68Displaying information within a window.68
Displaying information within a window.68myrajendra
 
Unit-2 swing and mvc architecture
Unit-2 swing and mvc architectureUnit-2 swing and mvc architecture
Unit-2 swing and mvc architectureAmol Gaikwad
 
Java Fx Overview Tech Tour
Java Fx Overview Tech TourJava Fx Overview Tech Tour
Java Fx Overview Tech TourCarol McDonald
 
Intro to JavaFX & Widget FX
Intro to JavaFX & Widget FXIntro to JavaFX & Widget FX
Intro to JavaFX & Widget FXStephen Chin
 
Java Graphics
Java GraphicsJava Graphics
Java GraphicsShraddha
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1PRN USM
 
Applets - lev' 2
Applets - lev' 2Applets - lev' 2
Applets - lev' 2Rakesh T
 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window ToolkitRutvaThakkar1
 
Graphics software
Graphics softwareGraphics software
Graphics softwareMohd Arif
 
PDF ON JAVA - JFC CONCEPT
PDF ON JAVA - JFC CONCEPTPDF ON JAVA - JFC CONCEPT
PDF ON JAVA - JFC CONCEPTNAVYA RAO
 
Dynamic Graph Plotting with WPF
Dynamic Graph Plotting with WPFDynamic Graph Plotting with WPF
Dynamic Graph Plotting with WPFIJERD Editor
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderAndres Almiray
 
OpenJFX on Android and Devices
OpenJFX on Android and DevicesOpenJFX on Android and Devices
OpenJFX on Android and DevicesStephen Chin
 

Similar to U5 JAVA.pptx (20)

Displaying information within a window.68
Displaying information within a window.68Displaying information within a window.68
Displaying information within a window.68
 
L18 applets
L18 appletsL18 applets
L18 applets
 
Unit-2 swing and mvc architecture
Unit-2 swing and mvc architectureUnit-2 swing and mvc architecture
Unit-2 swing and mvc architecture
 
Java Fx Overview Tech Tour
Java Fx Overview Tech TourJava Fx Overview Tech Tour
Java Fx Overview Tech Tour
 
Intro to JavaFX & Widget FX
Intro to JavaFX & Widget FXIntro to JavaFX & Widget FX
Intro to JavaFX & Widget FX
 
Applet in java new
Applet in java newApplet in java new
Applet in java new
 
Java Graphics
Java GraphicsJava Graphics
Java Graphics
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
13457272.ppt
13457272.ppt13457272.ppt
13457272.ppt
 
Applets - lev' 2
Applets - lev' 2Applets - lev' 2
Applets - lev' 2
 
Abstract Window Toolkit
Abstract Window ToolkitAbstract Window Toolkit
Abstract Window Toolkit
 
Graphics software
Graphics softwareGraphics software
Graphics software
 
Java chapter 7
Java chapter 7Java chapter 7
Java chapter 7
 
Gui
GuiGui
Gui
 
PDF ON JAVA - JFC CONCEPT
PDF ON JAVA - JFC CONCEPTPDF ON JAVA - JFC CONCEPT
PDF ON JAVA - JFC CONCEPT
 
Graphics in C++
Graphics in C++Graphics in C++
Graphics in C++
 
Dynamic Graph Plotting with WPF
Dynamic Graph Plotting with WPFDynamic Graph Plotting with WPF
Dynamic Graph Plotting with WPF
 
CodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilderCodeMash - Building Rich Apps with Groovy SwingBuilder
CodeMash - Building Rich Apps with Groovy SwingBuilder
 
Intake 38 6
Intake 38 6Intake 38 6
Intake 38 6
 
OpenJFX on Android and Devices
OpenJFX on Android and DevicesOpenJFX on Android and Devices
OpenJFX on Android and Devices
 

More from madan r

U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptxmadan r
 
U1 JAVA.pptx
U1 JAVA.pptxU1 JAVA.pptx
U1 JAVA.pptxmadan r
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptxmadan r
 
U2 JAVA.pptx
U2 JAVA.pptxU2 JAVA.pptx
U2 JAVA.pptxmadan r
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptxmadan r
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptxmadan r
 
UNIT 4.pptx
UNIT 4.pptxUNIT 4.pptx
UNIT 4.pptxmadan r
 
UNIT 3.pptx
UNIT 3.pptxUNIT 3.pptx
UNIT 3.pptxmadan r
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptxmadan r
 

More from madan r (9)

U3 JAVA.pptx
U3 JAVA.pptxU3 JAVA.pptx
U3 JAVA.pptx
 
U1 JAVA.pptx
U1 JAVA.pptxU1 JAVA.pptx
U1 JAVA.pptx
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
U2 JAVA.pptx
U2 JAVA.pptxU2 JAVA.pptx
U2 JAVA.pptx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 
UNIT 4.pptx
UNIT 4.pptxUNIT 4.pptx
UNIT 4.pptx
 
UNIT 3.pptx
UNIT 3.pptxUNIT 3.pptx
UNIT 3.pptx
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 

Recently uploaded

UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 

Recently uploaded (20)

UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 

U5 JAVA.pptx

  • 1. UNIT V EVENT DRIVEN PROGRAMMING Introducing Graphics – Working with color, font and images – Introduction to AWT – Origins of Swing – Two Key Swing Features – MVC Connection – Components and Containers – The Swing Packages – A Simple Swing Application – Event handling – Creating a Swing Applet – Exploring Swing : JLabel, ImageIcon, JTextField, The Swing Buttons, JScrollPane, JList and JComboBox – Creating Menus. 1
  • 2. Introducing Graphics • The java.awt.Graphics class provides many methods for graphics programming. • A graphics context is encapsulated by the Graphics class and is obtained in two ways: • It is passed to an applet when one of its various methods, such as paint( ) or update( ) is called. • It is returned by the getGraphics( ) method of Component. 2
  • 3. Graphics Methods Method Description abstract Graphics create() Creates a new Graphics object that is a copy ofthis Graphics object abstract void drawString(String str, int x, int y) Draws the text given by the specified string void drawRect(int x, int y, int width, int height) draws a rectangle with the specified width and height void draw3DRect(int x, int y, int width, int height, boolean raised) Draws a 3-D highlighted outline of the specified rectangle. abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) Draws an outlined round-cornered rectangle using this graphics context's current color abstract void fillRect(int x, int y, int width, int height) fill rectangle with the default color and specified width and height. 3
  • 4. Method Description abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) Draws a closed polygon defined by arrays of x and y coordinates. abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) Fills a closed polygon defined by arrays of x and y coordinates. abstract void drawOval(int x, int y, int width, int height) draw oval with the specified width and height. abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) fill a circular or elliptical arc. abstract void setColor(Color c) set the graphics current color to the specified color. abstract void setFont(Font font) set the graphics current font to the specified font. 4
  • 5. Example: import java.applet.Applet; import java.awt.*; public class Graphics1 extends Applet{ public void paint(Graphics g){ g.setColor(Color.red); g.drawString("Welcome",50, 50); g.drawLine(20,30,20,300); g.drawRect(70,100,30,30); g.fillRect(170,100,30,30); g.drawOval(70,200,30,30); g.setColor(Color.pink); g.fillOval(170,200,30,30); g.drawArc(90,150,30,30,30,270); g.fillArc(270,150,30,30,0,180); } } <html> <body> <applet code="Graphics1.class" width="300" height="300"> </applet> </body> </html> 5
  • 6. 6
  • 7. UNIT V EVENT DRIVEN PROGRAMMING Introducing Graphics – Working with color, font and images – Introduction to AWT – Origins of Swing – Two Key Swing Features – MVC Connection – Components and Containers – The Swing Packages – A Simple Swing Application – Event handling – Creating a Swing Applet – Exploring Swing : JLabel, ImageIcon, JTextField, The Swing Buttons, JScrollPane, JList and JComboBox – Creating Menus. 7
  • 8. Working with color, font and images • To support different colors Java package comes with the Color class. The Color class states colors in the default RGB color space or colors in arbitrary color spaces identified by a ColorSpace. • Color class static color variable available are: 8
  • 9. • Color.black • Color.lightGray • Color.blue • Color.magenta • Color.cyan • Color.orange • Color.darkGray • Color.pink • Color.gray • Color.red • Color.green • Color.white • Color.yellow 9
  • 10. Color class constructor • Color(float r, float g, float b) – create color with specified red, green, and blue values in the range (0.0 - 1.0) • Color(int r, int g, int b)- create color with the specified red, green, and blue values in the range (0 - 255). Method Description int getRed() Returns the red component in the range 0-255 in the default sRGB space. int getGreen() Returns the green component in the range 0- 255 in the default sRGB space int getBlue() Returns the blue component in the range 0-255 in the default sRGB space. Color getHSBColor(float h, float s, float b) Creates a Color object based on the specified values for the HSB color model. 10
  • 11. Fonts in Java & Font class constructor • The Font class states fonts, which are used to render text in a visible way. • Font(Fontfont) //Creates a new Font from the specifiedfont. • Font(String name, int style,intsize) //Creates a new Font from the specified name, style and pointsize 11
  • 12. 12
  • 13. import java.awt.*; import java.applet.*; public class colo extends Applet { Font f1,f2,f3; public void init() { f1 = new Font("Arial",Font.BOLD,18); f2 = new Font("Forte",Font.PLAIN,24); f3 = new Font("Elephant",Font.ITALIC,28) ; } public void paint(Graphics g) { setBackground(Color.yellow); g.setColor(Color.red); g.drawString(“Kongunadu",50,50); g.setColor(Color.blue); g.setFont(f1); g.drawString(“CSE",50,80); g.setColor(Color.green); g.setFont(f2); g.drawString(“Second Year",50,110); g.setColor(Color.magenta); g.setFont(f3); g.drawString(“Welcome",50,140); } } 13
  • 14. 14
  • 15. Images in Java • Image control is superclass for all image classes representing graphical images. Image class constructor Image()// create an Image object 15
  • 16. import java.awt.*; import java.applet.*; public class DisplayImage extends Applet { Image picture; public void init() { picture = getImage(getDocumentBase(),“kongu.jpg"); } public void paint(Graphics g) { g.drawImage(picture, 30,30, this); } } <html> <body> <applet code="DisplayImage.class" width="300" height="300"> </applet> </body> </html> 16
  • 17. UNIT V EVENT DRIVEN PROGRAMMING Introducing Graphics – Working with color, font and images – Introduction to AWT – Origins of Swing – Two Key Swing Features – MVC Connection – Components and Containers – The Swing Packages – A Simple Swing Application – Event handling – Creating a Swing Applet – Exploring Swing : JLabel, ImageIcon, JTextField, The Swing Buttons, JScrollPane, JList and JComboBox – Creating Menus. 17
  • 18. Introduction to AWT • The Abstract Window Toolkit (AWT) is Java's original platform- independent windowing, graphics, and user-interface widget toolkit. The AWT classes are contained in the java.awt package. • Contains all of the classes for creating user interfaces and for painting graphics and images. • An API to develop GUI or window-based applications in java. 18
  • 19. 19
  • 20. • Component A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. Examples : buttons, checkboxes, and scrollbars • Container The Container class is the subclass of Component. The container object is a component that can contain other AWT components. • Window The class Window is a top level window with no border and no menubar. The default layout for a window is BorderLayout. A window must have either a frame, dialog, or another window defined as its owner when it's constructed. 20
  • 21. • Panel It provides space in which an application can attach any other component, including other panels. The default layout manager for a panel is the FlowLayout layout manager • Frame A Frame is a top-level window with a title and a border. It uses BorderLayout as default layout manager. • Dialog A Dialog is a top-level window with a title and a border that is typically used to take some form of input from the user. • Canvas A Canvas component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user. The paint method must be overridden in order to perform custom graphics on the canvas. It is not a part of hierarchy of JavaAWT. 21
  • 22. • Frame Constructor Frame() Constructs a new instance of Frame that is initially invisible. Frame(String) 22
  • 23. 23
  • 24. Creating a Frame • We can generate a window by creating an instance of Frame. • The created frame can be made visible by calling setVisible( ). • When created, the window is given a default height and width. The size of the window can be changed explicitly by calling the setSize( ) method. • A label can be added to the current frame by creating an Label instance and calling the add() method. 24
  • 25. import java.awt.*; public class AwtFrame1{ public static void main(String[] args){ Frame frm = new Frame("Java AWT Frame"); Label lbl = new Label("Kongunadu College of Engg.& Tech.",Label.CENTER); frm.add(lbl); frm.setSize(400,400); frm.setVisible(true); } } 25
  • 26. UNIT V EVENT DRIVEN PROGRAMMING Introducing Graphics – Working with color, font and images – Introduction to AWT – Origins of Swing – Two Key Swing Features – MVC Connection – Components and Containers – The Swing Packages – A Simple Swing Application – Event handling – Creating a Swing Applet – Exploring Swing : JLabel, ImageIcon, JTextField, The Swing Buttons, JScrollPane, JList and JComboBox – Creating Menus. 26
  • 27. MVC • Model designs based on MVC architecture follow the MVC design pattern and they separate the application logic from the user interface when designing software. As the name implies MVC pattern has three layers, which are: • Model – Represents the business layer of the application • View – Defines the presentation of the application • Controller – Manages the flow of the application 27
  • 28. Implementation of MVC using Java • To implement a web application based on MVC design pattern, we will create • Employee Class, which acts as the model layer • Employee View Class, which defines the presentation layer (view layer) • Employee Controller Class, which acts as a controller 28
  • 29. The Model Layer • In the MVC design pattern, the model is the data layer which defines the business logic of the system and also represents the state of the application. • The model objects retrieve and store the state of the model in a database Now, let’s create a model using Employee Class. 29
  • 30. public class Employee { // declaring the variables private String EmployeeName; private String EmployeeId; private String EmployeeDepartment; // defining getter and setter methods public String getId() { return EmployeeId; } public void setId(String id) { this.EmployeeId = id; } public String getName() { return EmployeeName; } public void setName(String name) { this.EmployeeName = name; } public String getDepartment() { return EmployeeDepartment; } public void setDepartment(String Department) { this.EmployeeDepartment = Department; } } The Model Layer 30
  • 31. The View Layer // class which represents the view public class EmployeeView { // method to display the Employee details public void printEmployeeDetails (String EmployeeName, String EmployeeId, String EmployeeDepartment) { System.out.println("Employee Details: "); System.out.println("Name: " + EmployeeName); System.out.println("Employee ID: " + EmployeeId); System.out.println("Employee Department: " + EmployeeDepartment); } } 31
  • 32. The Controller Layer public class EmployeeController { private Employee model; private EmployeeView view; // constructor to initialize public EmployeeController(Employee model, EmployeeVi ew view) { this.model = model; this.view = view; } // getter and setter methods public void setEmployeeName(String name){ model.setName(name); } public String getEmployeeName(){ return model.getName(); } } public void setEmployeeId(String id){ model.setId(id); } public String getEmployeeId(){ return model.getId(); } public void setEmployeeDepartment(String Departm { model.setDepartment(Department); } public String getEmployeeDepartment(){ return model.getDepartment(); } // method to update view public void updateView() { view.printEmployeeDetails(model.getName(), model.g ), model.getDepartment()); } 32
  • 33. Main Class Java file public class MVCMain { public static void main(String[] args) { // fetching the employee record based on the employee_id from the database Employee model = retriveEmployeeFromDatabase(); // creating a view to write Employee details on console EmployeeView view = new EmployeeView(); EmployeeController controller = new EmployeeController(mode l, view); controller.updateView(); //updating the model data controller.setEmployeeName("Nirnay"); System.out.println("n Employee Details after updating: "); controller.updateView(); } private static Employee retriveEmployeeFromDatabase Employee Employee = new Employee(); Employee.setName("Anu"); Employee.setId("11"); Employee.setDepartment("Salesforce"); return Employee; } } 33
  • 34. Output Employee Details: Name: Anu Employee ID: 11 Employee Department: Salesforce Employee Details after updating: Name: Nirnay Employee ID: 11 Employee Department: Salesforce 34
  • 35. UNIT V EVENT DRIVEN PROGRAMMING Introducing Graphics – Working with color, font and images – Introduction to AWT – Origins of Swing – Two Key Swing Features – MVC Connection – Components and Containers – The Swing Packages – A Simple Swing Application – Event handling – Creating a Swing Applet – Exploring Swing : JLabel, ImageIcon, JTextField, The Swing Buttons, JScrollPane, JList and JComboBox – Creating Menus. 35
  • 36. Components and Containers • In Java, a component is the basic user interface object and is found in all Java applications. Components include lists, buttons, panels, and windows. • Swing provides the following useful top-level containers, all of which inherit from JComponent: 36
  • 37. JWindow • JWindow is a top-level window that doesn't have any trimmings and can be displayed anywhere on a desktop. • JWindow is a heavyweight component. You usually use JWindow to create pop-up windows and "splash" screens. JWindow extends AWT's Window class. 37
  • 38. JFrame • JFrame is a top-level window that can contain borders and menu bars. JFrame is a subclass of JWindow and is thus a heavyweight component. JDialog • JDialog is a lightweight component that you use to create dialog windows. You can place dialog windows on a JFrame or JApplet. JDialog extends AWT's Dialog class. 38
  • 39. JApplet • JApplet is a container that provides the basis for applets that run within web browsers. JApplet is a lightweight component that can contain other graphical user interface (GUI) components. JApplet extends AWT's Applet class. 39
  • 40. • All Swing components - including the JApplet and JDialog containers - need to be contained at some level inside a JWindow or JFrame. 40
  • 41. • Each top-level container consists of the following panes: Root pane • The root pane is an intermediate container that manages the layered pane, content pane, and glass pane. • It can also manage an optional menu bar. 41
  • 42. Layered pane • The layered pane contains the content pane and the optional menu bar. It can also contain other components, which it arranges so that they overlap each other. Content pane • It covers the visible section of the JFrame or JWindow and you use it to add components to the display area.. 42
  • 43. UNIT V EVENT DRIVEN PROGRAMMING Introducing Graphics – Working with color, font and images – Introduction to AWT – Origins of Swing – Two Key Swing Features – MVC Connection – Components and Containers – The Swing Packages – A Simple Swing Application – Event handling – Creating a Swing Applet – Exploring Swing : JLabel, ImageIcon, JTextField, The Swing Buttons, JScrollPane, JList and JComboBox – Creating Menus. 43
  • 44. Event handling • Any change in the state of any object is called event. • For Example: Pressing a button, entering a character in Textbox, Clicking or dragging a mouse, etc. • The three main components in event handling are: • Events • Events Source • Listeners 44
  • 45. • Events: An event is a change in state of an object. For example, mouseClicked,mousePressed. • Events Source: Event source is an object that generates an event. Example: a button, frame, textfield. • Listeners: A listener is an object that listens to the event. A listener gets notified when an event occurs. When listener receives an event, it process it and then return. • Listeners are group of interfaces and are defined in java.awt.event package. Each component has its own listener. For example MouseListener handles allMouseEvent 45
  • 46. 46
  • 47. import java.awt.*; import java.awt.event.*; public class MouseListenerExample extends Frame implements MouseListener{ Label l; MouseListenerExample(){ addMouseListener(this); l=new Label(); l.setBounds(20,50,100,20); add(l); setSize(300,300); setLayout(null); setVisible(true); } public void mouseClicked(MouseEvent e) { l.setText("Mouse Clicked"); } public void mouseEntered(MouseEvent e) { l.setText("Mouse Entered"); } public void mouseExited(MouseEvent e) { l.setText("Mouse Exited"); } public void mousePressed(MouseEvent e) { l.setText("Mouse Pressed"); } public void mouseReleased(MouseEvent e) { l.setText("Mouse Released"); } public static void main(String[] args) { new MouseListenerExample(); } } 47
  • 48. 48
  • 49. UNIT V EVENT DRIVEN PROGRAMMING Introducing Graphics – Working with color, font and images – Introduction to AWT – Origins of Swing – Two Key Swing Features – MVC Connection – Components and Containers – The Swing Packages – A Simple Swing Application – Event handling – Creating a Swing Applet – Exploring Swing : JLabel, ImageIcon, JTextField, The Swing Buttons, JScrollPane, JList and JComboBox – Creating Menus. 49
  • 50. 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. 50
  • 51. Swing Features • Light Weight - • Rich controls -like Tree, TabbedPane, slider, colourpicker, tablecontrols • Highly Customizable - controls can be customized in very easy way as visual appearance. • Pluggable look-and-feel- SWING based GUI Application look and feel can be changed at run time based on available values. 51
  • 52. 52
  • 53. The following program is an example for Java Swing. import javax.swing.*; public class FirstSwingExample { public static void main(String[] args) { JFrame f=new JFrame();//creating instance of JFrame JButton b=new JButton("click"); //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 } } 53
  • 54. The following program is an example for Java Swing. import javax.swing.*; public class FirstSwingExample { public static void main(String[] args) { JFrame f=new JFrame(); JButton b=new JButton("click"); b.setBounds(130,100,100, 40);//x axis, y axis, width, height f.add(b); f.setSize(400,500);//400 width and 500 height f.setLayout(null); f.setVisible(true); } } 54
  • 55. import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.WindowConstants; import javax.swing.SwingUtilities; public class SwingExample3 implements Runnable { public void run() { JFrame f = new JFrame("Swingexample"); f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) ; f.setLayout(new FlowLayout()); f.add(new JLabel("JAVA PROGRAMMING!")); f.add(new JButton("OK")); f.pack(); f.setVisible(true); } public static void main(String[] args) { SwingExample3 se = new SwingExample3(); SwingUtilities.invokeLater(se); } } 55
  • 56. Layout management • Java LayoutManagers • The LayoutManagers are used to arrange components in a particular manner. 1. java.awt.BorderLayout 2. java.awt.FlowLayout 3. java.awt.GridLayout 4. java.awt.CardLayout 5. java.awt.GridBagLayout 6. javax.swing.BoxLayout 7. javax.swing.GroupLayout 8. javax.swing.ScrollPaneLayout 9. javax.swing.SpringLayoutetc. 56
  • 57. Java BorderLayout • The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. • Each region (area) may contain one component only. It is the default layout of frame or window. • 1. public static final intNORTH • 2. public static final intSOUTH • 3. public static final intEAST • 4. public static final intWEST • 5. public static final intCENTER 57
  • 58. Java 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 arow. 2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between thecomponents. 3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns alongwith given horizontal and verticalgaps. 58
  • 59. import java.awt.*; import javax.swing.*; public class GridE2 { JFrame f; GridE2() { 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"); JButton b6=new JButton("6"); JButton b7=new JButton("7"); JButton b8=new JButton("8"); f.add(b1); f.add(b2); f.add(b3); f.add(b4); f.add(b5); f.add(b6); f.add(b7); f.add(b8); f.setLayout(new GridLayout(2,4)); //setting grid layout of 3 rows and 3 columns f.setSize(300,300); f.setVisible(true); } } public static void main(String[] args) { new GridE2(); } 59
  • 60. 60
  • 61. 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. • Fields of FlowLayout class 1. public static final intLEFT 2. public static final intRIGHT 3. public static final int CENTER 4. public static final intLEADING 5. public static final intTRAILING 61
  • 62. Constructors of FlowLayoutclass • 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 verticalgap. • 3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given horizontal and verticalgap. 62
  • 63. import java.awt.*; import javax.swing.*; public class FlowE1{ JFrame f; FlowE1() { 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.LEFT)); //setting flow layout of left alignment f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new FlowE1(); } } 63
  • 64. Java BoxLayout • The BoxLayout is used to arrange the components either vertically or horizontally. For this purpose, BoxLayout provides four constants. They are as follows: • Fields of BoxLayout class 1. public static final intX_AXIS 2. public static final intY_AXIS 3. public static final intLINE_AXIS 4. public static final intPAGE_AXIS 64
  • 65. 65
  • 66. Java GridBagLayout • The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline. The components may not be of same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells. 66
  • 67. import java.awt.Button; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.*; public class GridBagLayoutExample extends JFrame { public static void main(String[] args) { GridBagLayoutExample a = new GridBagLayoutExample(); } public GridBagLayoutExample() { GridBagLayoutgrid = new GridBagLayout(); GridBagConstraints gbc = new GridBagConstraints(); setLayout(grid); setTitle("GridBag Layout Example"); GridBagLayout layout = new GridBagLayout(); this.setLayout(layout); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy =0; this.add(new Button("Button One"), gbc); gbc.gridx = 1; gbc.gridy =0; this.add(new Button("Button two"), gbc); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.ipady = 20; gbc.gridx =0; gbc.gridy =1; this.add(new Button("Button Three"), gbc); gbc.gridx = 1; gbc.gridy =1; this.add(new Button("Button Four"), gbc); gbc.gridx = 0; gbc.gridy =2; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = 2; this.add(new Button("Button Five"), gbc); setSize(300, 300); setPreferredSize(getSize()); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } } 67
  • 68. 68
  • 69. Java SpringLayout • A SpringLayout arranges the children of its associated container according to a set of constraints. Constraints are nothing but horizontal and vertical distance between two component edges. Every constrains are represented by a SpringLayout.Constraint object. 69
  • 70. Swing Components • The Swing components Text Fields, Text Areas and Buttons are explained. 70
  • 71. • Swing Components and Containers • A component is an independent visual control. Swing Framework contains a large set of components which provide rich functionalities and allow high level of customization. • They all are derived from JComponent class. All these components are lightweight components. • This class provides some common functionality like pluggable look and feel, support for accessibility, drag and drop, layout, etc. • A container holds a group of components. It provides a space where a component can be managed and displayed. Containers are of two types: • 1. Top level Containers • 2. LightweightContainers 71
  • 72. 72
  • 73. import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.UIManager; public class TextAreaE1 { public static void main(String[] args) { JFrame f = new JFrame("Text Area Examples"); JPanel upperPanel = new JPanel(); JPanel lowerPanel = new JPanel(); f.getContentPane().add(upperPanel, "North"); f.getContentPane().add(lowerPanel, "South"); upperPanel.add(new JTextArea(content)); upperPanel.add(new JTextArea(content, 6, 10)); upperPanel.add(new JTextArea(content, 3, 8)); lowerPanel.add(new JScrollPane(new JTextArea(content, 6, 8))); JTextArea ta = new JTextArea(content, 6, 8); ta.setLineWrap(true); lowerPanel.add(new JScrollPane(ta)); ta = new JTextArea(content, 6, 8); ta.setLineWrap(true); ta.setWrapStyleWord(true); lowerPanel.add(new JScrollPane(ta)); f.pack(); f.setVisible(true); } static String content = "JAVA PROGRAMMING"; } 73
  • 74. 74
  • 75. TextField • JTextField is used for taking input of single line of text. It is most widely used text component. It has three constructors, • JTextField(intcols) • JTextField(String str, intcols) • JTextField(Stringstr) 75
  • 76. import java.awt.event.*; import java.awt.*; public class TextFieldE1 extends JFrame { public TextFieldE1() { JTextField jtf =newJTextField(20); //creating JTextField. add(jtf); //adding JTextField to frame. setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400,400); setVisible(true); } public static void main(String[] args) { new TextFieldE1(); } } 76
  • 77. Button: • JButton class provides functionality of a button. JButton class has three constructors. JButton(Iconic) JButton(Stringstr) JButton(String str, Iconic) • It allows a button to be created using icon, a string or both. JButton supports ActionEvent. When a button is pressed an ActionEvent is generated. 77
  • 78. import javax.swing.*; import java.awt.event.*; import java.awt.*; public class testbutton extends JFrame { testbutton() { JButton bt1 = new JButton("OK"); JButton bt2 = new JButton("NOt OK"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting close operation. setLayout(newFlowLayout()); //setting layout using FlowLayout object setSize(400,400); //setting size ofJframe add(bt1); //adding Yes button toframe. add(bt2); //adding No button toframe. setVisible(true); } public static void main(String[] args) { new testbutton(); } } 78
  • 79. JCheckBox • JCheckBox class is used to create checkboxes inframe. • It is used to turn an option on (true) or off (false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on". • It inherits JToggleButtonclass. 79
  • 80. import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Test extends JFrame { public Test() {{ JCheckBox jcb = new JCheckBox("Correct"); //creating JCheckBox. add(jcb); //adding JCheckBox to frame. jcb =newJCheckBox("Wrong"); //creating JCheckBox. add(jcb); //adding JCheckBox toframe. jcb =newJCheckBox("Maybe"); //creating JCheckBox. add(jcb); //adding JCheckBox to frame. setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400); setVisible(true); } public static void main(String[] args) { new Test(); } } 80
  • 81. JRadioButton • JRadioButton class is used to create a radio button in Frames. • It is used to choose one option from multipleoptions. • It is widely used in exam systems or quiz. • It should be added in ButtonGroup to select one radio button only 81
  • 82. import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Test extends JFrame { public Test() { JRadioButton jcb =newJRadioButton("Male"); add(jcb); jcb =newJRadioButton("Female"); add(jcb); // jcb = newJRadioButton("Transgender"); add(jcb); setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400); setVisible(true); } public static void main(String[] args) { new Test(); } } 82
  • 83. Java JList • The object of JList class represents a list of textitems. • The list of text items can be set up so that the user can choose either one item or multipleitems. • It inherits JComponentclass. 83
  • 84. import javax.swing.*; public class Test22 { Test() { JFrame f= new JFrame(); DefaultListModel<String> l1 = new DefaultListModel<>(); l1.addElement("CSE"); l1.addElement("IT"); l1.addElement("ECE"); l1.addElement("EEE"); l1.addElement("CIVIL"); l1.addElement("MECHANICAL"); JList<String> list = new JList<>(l1); list.setBounds(100,100, 75,75); f.add(list); f.setSize(900,900); f.setLayout(null); f.setVisible(true); } public static void main(String args[]) { new Test22(); } } 84
  • 85. Java JMenuBar, JMenu and JMenuItem Creating Menus • The JMenuBar class is used to display menubar on the window or frame. It may have several menus. • The Menu class represents the pull-down menu component which is deployed from a menubar. • A JMenu is a container that can hold menu items that represent theoptions. • The object of JMenu class is a pull down menu component which is displayed from the menu bar. It inherits the JMenuItemclass. • The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must belong to the JMenuItem or any of itssubclass. 85
  • 86. import javax.swing.*; public class MenuExample { JMenu menu, submenu; JMenuItem i1, i2, i3, i4, i5, i6, i7; MenuExample(){ JFrame f= new JFrame("Menu and MenuItem Example"); JMenuBar mb=new JMenuBar(); menu=new JMenu("File Menu"); submenu=new JMenu("Print"); i1=new JMenuItem("New"); i2=new JMenuItem("Open"); i3=new JMenuItem("Save"); i4=new JMenuItem("Save As"); i5=new JMenuItem("Print"); i6=new JMenuItem("Quick Print"); i7=new JMenuItem("Print Preview"); menu.add(i1); menu.add(i2); menu.add(i3); menu.add(i4); submenu.add(i5); submenu.add(i6); submenu.add(i7); menu.add(submenu); mb.add(menu); f.setJMenuBar(mb); f.setSize(400,400); f.setLayout(null); f.setVisible(true); } public static void main(String args[]) { new MenuExample(); } } 86
  • 87. 87