Unit1 Swing
Unit1 Swing
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
1
Commonly used Methods of Component class.
The methods of Component class are widely used in java swing that are given below.
Method Description
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
We can write the code of swing inside the main(), constructor or any other method.
Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.
File: FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("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
}
}
Output:
2
Example of Swing by Association inside constructor
We can also write all the codes of creating JFrame, JButton and method call inside the java
constructor.
File: Simple.java
import javax.swing.*;
public class Simple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);
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
}
public static void main(String[] args) {
new Simple();
}
}
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the
position of the button.
We can also inherit the JFrame class, so there is no need to create the instance of JFrame class
explicitly.
3
File: Simple2.java
import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
Example:
// using association
import javax.swing.*;
JFrame frame;
4
test1()
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(button);
frame.setSize(500, 600);
frame.setLayout(null);
frame.setVisible(true);
new test1();
5
Way 2: By extending Frame class (inheritance)
In this example, we will be inheriting JFrame class to create JFrame window and hence it
won’t be required to create an instance of JFrame class explicitly.
Example:
Output:
6
Way 3: Create a frame using Swing inside main()
Example 1:
Output:
7
1.3 Swing components
Swing components are the basic building blocks of an application. We know that Swing is a GUI
widget toolkit for Java. Every application has some basic interactive interface for the user. For
example, a button, check-box, radio-button, text-field, etc. These together form the components
in Swing. Swing components are the interactive elements in a Java application.
Top 13 Components of Swing in Java
Below are the different components of swing in java:
1. JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
8
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
2. JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.
9
}
}
Output:
3. JTextField
The object of a JTextField class is a text component that allows the editing of a single line text. It
inherits JTextComponent class.
10
f.setVisible(true);
}
}
Output:
4. JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class
11
{
new TextAreaExample();
}
}
Output:
5. JPasswordField
The object of a JPasswordField class is a text component specialized for password entry. It
allows the editing of a single line of text. It inherits JTextField class.
JPasswordField class declaration
public class JPasswordField extends JTextField
Example
import javax.swing.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
12
6. JCheckBox
The JCheckBox class is used to create a checkbox. 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 JToggleButton class.
Output:
13
7. JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
14
8. JList
The object of JList class represents a list of text items. The list of text items can be set up so that
the user can choose either one item or multiple items. It inherits JComponent class.
Output:
15
9. JComboBox
JComboBox class is used to render a dropdown of the list of options.
16
1.4 Working with 2D Shapes
In general, a two dimensional shape can be defined as the geometrical figure that can be drawn
on the coordinate system consist of X and Y planes. However, this is different from 3D shapes in
the sense that each point of the 2D shape always consists of two coordinates (X,Y). Using
JavaFX, we can create 2D shapes such as Line, Rectangle, Circle, Ellipse, Polygon, Cubic
Curve, quad curve, Arc, etc. The class javafx.scene.shape.Shape is the base class for all the shape
classes.
As we have mentioned earlier that every shape is represented by a specific class of the
package javafx.scene.shape. For creating a two dimensional shape, the following instructions
need to be followed.
2. Set the required properties for the class using instance setter methods: for example,
rect.setX(10);
rect.setY(20);
rect.setWidth(100);
rect.setHeight(100);
The following table consists of the JavaFX shape classes along with their descriptions.
Shape Description
17
Line In general, Line is the geometrical figure which joins two (X,Y) points on 2D coordinate
system. In JavaFX, javafx.scene.shape.Line class needs to be instantiated in order to create
lines.
Rectangle In general, Rectangle is the geometrical figure with two pairs of two equal sides and four
right angles at their joint. In JavaFX, javafx.scene.shape.Rectangle class needs to be
instantiated in order to create Rectangles.
Ellipse In general, ellipse can be defined as a curve with two focal points. The sum of the distances to
the focal points are constant from each point of the ellipse.
In JavaFX. javafx.scene.shape.Ellipse class needs to be instantiated in order to create Ellipse.
Arc Arc can be defined as the part of the circumference of the circle of ellipse.
In JavaFX, javafx.scene.shape.Arc class needs to be instantiated in order to create Arcs.
Circle A circle is the special type of Ellipse having both the focal points at the same location.
In JavaFX, Circle can be created by instantiating javafx.scene.shape.Circle class.
Polygon Polygon is a geometrical figure that can be created by joining the multiple Co-planner
line segments. In JavaFX, javafx.scene.shape. Pollygon class needs to be instantiated in order
to create polygon.
Method explanation
18
Method explanation
getHSBColor(float h, float s, Creates a Color object based on the specified values for the
float b) HSB color model.
19
ColorEx()
{
// create a new Color
Color c = Color.yellow;
// create a panel
JPanel p = new JPanel();
p.setBackground(c);
setSize(200, 200);
add(p);
show();
}
// Main Method
public static void main(String args[])
{
ColorEx c = new ColorEx();
}
}
Output :
Class declaration
Following is the declaration for java.awt.Font class:
public class Font
extends Object
implements Serializable
Field
Following are the fields for java.awt.geom.Arc2D class:
static int BOLD -- The bold style constant.
20
static int CENTER_BASELINE --The baseline used in ideographic scripts like Chinese,
Japanese, and Korean when laying out text.
static String DIALOG --A String constant for the canonical family name of the logical
font "Dialog".
static String DIALOG_INPUT --A String constant for the canonical family name of the
logical font "DialogInput".
static int HANGING_BASELINE -- The baseline used in Devanigiri and similar scripts
when laying out text.
static int ITALIC -- The italicized style constant.
static String SERIF -- A String constant for the canonical family name of the logical font
"Serif".
protected int size --The point size of this Font, rounded to integer.
protected int style -- The style of this Font, as passed to the constructor.
static int TRUETYPE_FONT -- Identify a font resource of type TRUETYPE.
static int TYPE1_FONT -- Identify a font resource of type TYPE1.
Class methods
S.N. Method & Description
1 boolean canDisplay(char c)
Checks if this Font has a glyph for the specified character.
21
17 Font deriveFont(int style, float size)
Creates a new Font object by replicating this Font object and applying a new style and size.
Font Example
Create the following java program using any editor of your choice in say D:/ > AWT > com >
tutorialspoint > gui >
AWTGraphicsDemo.java
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public AWTGraphicsDemo(){
super("Java AWT Examples");
prepareGUI();
}
22
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Font plainFont = new Font("Serif", Font.PLAIN, 24);
g2.setFont(plainFont);
g2.drawString("Welcome to TutorialsPoint", 50, 70);
Font italicFont = new Font("Serif", Font.ITALIC, 24);
g2.setFont(italicFont);
g2.drawString("Welcome to TutorialsPoint", 50, 120);
Font boldFont = new Font("Serif", Font.BOLD, 24);
g2.setFont(boldFont);
g2.drawString("Welcome to TutorialsPoint", 50, 170);
Font boldItalicFont = new Font("Serif", Font.BOLD+Font.ITALIC, 24);
g2.setFont(boldItalicFont);
g2.drawString("Welcome to TutorialsPoint", 50, 220);
}
}
output
23
Toolkit t=Toolkit.getDefaultToolkit();
Image i=t.getImage("p3.gif");
g.drawImage(i, 120,100,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);
}
}
1.8 Event Handling
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events.
Event Handling Example
Create the following java program using any editor of your choice in say D:/ > AWT > com >
tutorialspoint > gui >
AwtControlDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
24
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showEventDemo(){
headerLabel.setText("Control in action: Button");
Button okButton = new Button("OK");
Button submitButton = new Button("Submit");
Button cancelButton = new Button("Cancel");
okButton.setActionCommand("OK");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
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.");
}
}
}
}
Output:
25
1.9 Event classes
The classes that represent events are at the core of Java’s event handling mechanism. Thus, a
discussion of event handling must begin with the event classes. It is important to understand,
however, that Java defines several types of events and that not all event classes can be discussed
in this chapter. Arguably, the most widely used events at the time of this writing are those
defined by the AWT and those defined by Swing. This chapter focuses on the AWT events.
import javax.swing.*;
import javax.swing.event.*;
26
import java.awt.event.*;
//1st step: Implement ActionListener interface
public class MyJButtonActionListener implements ActionListener
{
private static JTextField text;
public static void main(String[] args)
{
JFrame frame = new JFrame("ActionListener Example");
text = new JTextField();
text.setBounds(45,50,150,20);
JButton btn = new JButton("Click here");
btn.setBounds(70,100,100,30);
MyJButtonActionListener instance = new MyJButtonActionListener();
//2nd step: Register the component with the Listener
btn.addActionListener(instance);
frame.add(btn);
frame.add(text);
frame.setSize(250,250);
frame.setLayout(null);
frame.setVisible(true);
}
//3rd step: Override the method actionPerformed()
public void actionPerformed(ActionEvent e){
text.setText("Welcome to StackHowTo");
}
}
Output
Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
27
using Adapter classes:
o It assists the unrelated classes to work combinedly.
o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
1. Java WindowAdapter
In the following example, we are implementing the WindowAdapter class of AWT and one its
methods windowClosing() to close the frame window.
/ importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// main method
public static void main(String[] args) {
new AdapterExample();
}
}
Output:
28
2. Java MouseAdapter
Example
In the following example, we are implementing the MouseAdapter class. The MouseListener
interface is added into the frame to listen the mouse event in the frame.
MouseAdapterExample.java
29
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 30, 30);
}
// main method
public static void main(String[] args) {
new MouseAdapterExample();
}
}
Output:
3. Java MouseMotionAdapter
In the following example, we are implementing the MouseMotionAdapter class and its different
methods to listen to the mouse motion events in the Frame window.
MouseMotionAdapterExample.java
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits the MouseMotionAdapter class
public class MouseMotionAdapterExample extends MouseMotionAdapter {
// object of Frame class
Frame f;
// class constructor
MouseMotionAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Motion Adapter");
// adding MouseMotionListener to the Frame
f.addMouseMotionListener (this);
// setting the size, layout and visibility of the frame
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
// overriding the mouseDragged() method
public void mouseDragged (MouseEvent e) {
30
// creating the Graphics object and fetching them from the Frame object using getGraphics() met
hod
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.ORANGE);
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 20, 20);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
}
}
Output:
4. Java KeyAdapter
In the following example, we are implementing the KeyAdapter class and its method.
KeyAdapterExample.java
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits the KeyAdapter class
public class KeyAdapterExample extends KeyAdapter {
// creating objects of Label, TextArea and Frame
Label l;
TextArea area;
Frame f;
// class constructor
KeyAdapterExample() {
// creating the Frame with title
f = new Frame ("Key Adapter");
// creating the Label
31
l = new Label();
// setting the location of label
l.setBounds (20, 50, 200, 20);
// creating the text area
area = new TextArea();
// setting the location of text area
area.setBounds (20, 80, 300, 300);
// adding KeyListener to text area
area.addKeyListener(this);
// adding the label and text area to frame
f.add(l);
f.add(area);
// setting the size, layout and visibility of frame
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}
// overriding the keyReleased() method
public void keyReleased (KeyEvent e) {
// creating the String object to get the text fromTextArea
String text = area.getText();
// splitting the String into words
String words[] = text.split ("\\s");
// setting the label text to print the number of words and characters of given string
l.setText ("Words: " + words.length + " Characters:" + text.length());
}
// main method
public static void main(String[] args) {
new KeyAdapterExample();
}
}
Output:
32
1.10.1 MVC Design Pattern
The Model View Controller (MVC) design pattern specifies that an application consist of a
data model, presentation information, and control information. The pattern requires that each
of these be separated into different objects.
MVC is more of an architectural pattern, but not for complete application. MVC mostly relates
to the UI / interaction layer of an application.
The Model contains only the pure application data, it contains no logic describing how to
present the data to a user.
The View presents the model’s data to the user. The view knows how to access the model’s
data, but it does not know what this data means or what the user can do to manipulate it.
The Controller exists between the view and the model. It listens to events triggered by the
view (or another external source) and executes the appropriate reaction to these events. In
most cases, the reaction is to call a method on the model. Since the view and the model are
connected through a notification mechanism, the result of this action is then automatically
reflected in the view.
In Java Programming, the Model contains the simple Java classes, the View used to
display the data and the Controller contains the servlets. Due to this separation the user
requests are processed as follows:
33
Figure 3: MVC Design Pattern
Advantages
Multiple developers can work simultaneously on the model, controller and views.
MVC enables logical grouping of related actions on a controller together. The views for a
specific model are also grouped together.
Models can have multiple views.
Disadvantages
The framework navigation can be complex because it introduces new layers of abstraction
and requires users to adapt to the decomposition criteria of MVC.
Knowledge on multiple technologies becomes the norm. Developers using MVC need to be
skilled in multiple technologies .
34
return EmployeeId;
}
35
System.out.println("Employee Department: " + EmployeeDepartment);
}
}
// class which represent the controller
public class EmployeeController {
// constructor to initialize
public EmployeeController(Employee model, EmployeeView view) {
this.model = model;
this.view = view;
}
36
model.setDepartment(Department);
}
// main class
public class MVCMain {
public static void main(String[] args) {
// fetching the employee record based on the employee_id from the database
Employee model = retriveEmployeeFromDatabase();
controller.updateView();
controller.updateView();
}
37
private static Employee retriveEmployeeFromDatabase(){
Employee Employee = new Employee();
Employee.setName("Anu");
Employee.setId("11");
Employee.setDepartment("Salesforce");
return Employee;
}
}
Output:
Employee Details:
Name: Anu
Employee ID: 11
Employee Department: Salesforce
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout managers.
There are the following classes that represent the layout managers:
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.SpringLayout etc.
1. 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 a frame or
window. The BorderLayout provides five constants for each region:
1. public static final int NORTH
38
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor
FileName: Border.java
import java.awt.*;
import javax.swing.*;
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
Output:
39
2. Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another (in a
flow). It is the default layout of the applet or panel.
Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
Example of FlowLayout class: Using FlowLayout() constructor
FileName: FlowLayoutExample.java
// import statements
import java.awt.*;
import javax.swing.*;
40
JFrame frameObj;
// constructor
FlowLayoutExample()
{
// creating a frame object
frameObj = new JFrame();
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}
41
Output:
3.Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.
Constructors of GridLayout class
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns along with given horizontal and vertical gaps.
Example of GridLayout class: Using GridLayout() Constructor
The GridLayout() constructor creates only one row. The following example shows the usage of
the parameterless constructor.
FileName: GridLayoutExample.java
// import statements
import java.awt.*;
import javax.swing.*;
// constructor
GridLayoutExample()
{
frameObj = new JFrame();
// creating 9 buttons
JButton btn1 = new JButton("1");
42
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
// main method
public static void main(String argvs[])
{
new GridLayoutExample();
}
}
Output:
43
4.Java CardLayout
The Java CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known as
CardLayout.
Constructors of CardLayout Class
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.
Commonly Used Methods of CardLayout Class
o public void next(Container parent): is used to flip to the next card of the given
container.
o public void previous(Container parent): is used to flip to the previous card of the given
container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given container.
o public void show(Container parent, String name): is used to flip to the specified card
with the given name.
CardLayout crd;
cPane = getContentPane();
44
cPane.setLayout(crd);
// adding listeners to it
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
// Upon clicking the button, the next card of the container is shown
// after the last card, again, the first card of the container is shown upon clicking
crd.next(cPane);
}
// main method
public static void main(String argvs[])
{
// creating an object of the class CardLayoutExample1
CardLayoutExample1 crdl = new CardLayoutExample1();
Output:
45
When the button named apple is clicked, we get
46
Again, we reach the first card of the container if the cat button is clicked, and the cycle
continues.
5.Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along their
baseline.
The components may not be of the same size. Each GridBagLayout object maintains a dynamic,
rectangular grid of cells. Each component occupies one or more cells known as its display area.
Each component associates an instance of GridBagConstraints. With the help of the constraints
object, we arrange the component's display area on the grid. The GridBagLayout manages each
component's minimum and preferred sizes in order to determine the component's size.
GridBagLayout components are also arranged in the rectangular grid but can have many
different sizes and can occupy multiple rows or columns.
1. import java.awt.Button;
2. import java.awt.GridBagConstraints;
3. import java.awt.GridBagLayout;
4. import javax.swing.*;
5. public class GridBagLayoutExample extends JFrame{
6. public static void main(String[] args) {
7. GridBagLayoutExample a = new GridBagLayoutExample();
8. }
9. public GridBagLayoutExample() {
10. GridBagLayoutgrid = new GridBagLayout();
11. GridBagConstraints gbc = new GridBagConstraints();
12. setLayout(grid);
47
13. setTitle("GridBag Layout Example");
14. GridBagLayout layout = new GridBagLayout();
15. this.setLayout(layout);
16. gbc.fill = GridBagConstraints.HORIZONTAL;
17. gbc.gridx = 0;
18. gbc.gridy = 0;
19. this.add(new Button("Button One"), gbc);
20. gbc.gridx = 1;
21. gbc.gridy = 0;
22. this.add(new Button("Button two"), gbc);
23. gbc.fill = GridBagConstraints.HORIZONTAL;
24. gbc.ipady = 20;
25. gbc.gridx = 0;
26. gbc.gridy = 1;
27. this.add(new Button("Button Three"), gbc);
28. gbc.gridx = 1;
29. gbc.gridy = 1;
30. this.add(new Button("Button Four"), gbc);
31. gbc.gridx = 0;
32. gbc.gridy = 2;
33. gbc.fill = GridBagConstraints.HORIZONTAL;
34. gbc.gridwidth = 2;
35. this.add(new Button("Button Five"), gbc);
36. setSize(300, 300);
37. setPreferredSize(getSize());
38. setVisible(true);
39. setDefaultCloseOperation(EXIT_ON_CLOSE);
40.
41. }
42.
43. }
Output:
48
6.java BoxLayout
The Java BoxLayout class is used to arrange the components either vertically or horizontally.
For this purpose, the BoxLayout class provides four constants.
1. public static final int X_AXIS: Alignment of the components are horizontal from left to
right.
2. public static final int Y_AXIS: Alignment of the components are vertical from top to
bottom.
3. public static final int LINE_AXIS: Alignment of the components is similar to the way
words are aligned in a line, which is based on the ComponentOrientation property of the
container.
4. public static final int PAGE_AXIS: Alignment of the components is similar to the way
text lines are put on a page, which is based on the ComponentOrientation property of the
container.
Example of BoxLayout class with Y-AXIS:
FileName: BoxLayoutExample1.java
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample1 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample1 () {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. // adding the buttons so that it can be displayed
13. add (buttons[i]);
14. }
15. // the buttons will be placed horizontally
16. setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
17. setSize(400,400);
18. setVisible(true);
19. }
20. // main method
21. public static void main(String args[]){
22. BoxLayoutExample1 b=new BoxLayoutExample1();
23. }
24. }
Output:
49
7.GroupLayout
GroupLayout groups its components and places them in a Container hierarchically. The
grouping is done by instances of the Group class.
Group is an abstract class, and two concrete classes which implement this Group class are
SequentialGroup and ParallelGroup.
SequentialGroup positions its child sequentially one after another whereas ParallelGroup aligns
its child on top of each other.
1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4. public class GroupExample {
5. public static void main(String[] args) {
6. JFrame frame = new JFrame("GroupLayoutExample");
7. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
8. Container contentPanel = frame.getContentPane();
9. GroupLayout groupLayout = new GroupLayout(contentPanel);
10.
11. contentPanel.setLayout(groupLayout);
12.
13. JLabel clickMe = new JLabel("Click Here");
14. JButton button = new JButton("This Button");
15.
16. groupLayout.setHorizontalGroup(
17. groupLayout.createSequentialGroup()
18. .addComponent(clickMe)
19. .addGap(10, 20, 100)
50
20. .addComponent(button));
21. groupLayout.setVerticalGroup(
22. groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
23. .addComponent(clickMe)
24. .addComponent(button));
25. frame.pack();
26. frame.setVisible(true);
27. }
28. }
Output:
8.ScrollPaneLayout
The layout manager is used by JScrollPane. JScrollPaneLayout is responsible for nine
components: a viewport, two scrollbars, a row header, a column header, and four "corner"
components.
1. import javax.swing.ImageIcon;
2. import javax.swing.JFrame;
3. import javax.swing.JLabel;
4. import javax.swing.JScrollPane;
5. public class ScrollPaneDemo extends JFrame
6. {
7. public ScrollPaneDemo() {
8. super("ScrollPane Demo");
9. ImageIcon img = new ImageIcon("child.png");
10.
11. JScrollPane png = new JScrollPane(new JLabel(img));
12.
13. getContentPane().add(png);
14. setSize(300,250);
15. setVisible(true);
16. }
17.
18. public static void main(String[] args) {
19. new ScrollPaneDemo();
20. }
21. }
Output:
51
9.SpringLayout Class
A SpringLayout class in AWT(Abstract Window Toolkit) laid out of the children to its
associated container, according to a set of Layout constraints. Each constraint is represented by a
Spring object which controls the vertical or horizontal distance between two component edges.
SpringLayout(): Used to constructs a new SpringLayout class.
// Main Method
public static void main(String[] arguments)
{
// main window
// Function to set the default look
// and feel decorated status of JFrame.
52
JFrame.setDefaultLookAndFeelDecorated(true);
// Initialization of object
// "b1" of JButton class.
Component b1 = new JButton("GEEKS");
// Initialization of object
// "b2" of JButton class.
Component b2 = new JButton("GFG");
// Initialization of object
// "b3" of JButton class.
Component b3 = new JButton("JAVA");
// Initialization of object
// "b4" of JButton class.
Component b4 = new JButton("Sudo Placement");
53
// Adding the JButton "b4" on frame
frame.add(b4);
layout.putConstraint(SpringLayout.NORTH, b1,
10, SpringLayout.NORTH, content);
layout.putConstraint(SpringLayout.NORTH, b2,
10, SpringLayout.SOUTH, b1);
layout.putConstraint(SpringLayout.NORTH, b3,
10, SpringLayout.SOUTH, b2);
layout.putConstraint(SpringLayout.NORTH, b4,
10, SpringLayout.NORTH, content);
54
UNIT 2 Database Programming
55
which manages objects of this type. It also abstracts the details associated with working
with Driver objects.
Connection − This interface with all methods for contacting a database. The connection
object represents communication context, i.e., all communication with database is
through connection object only.
Statement − You use objects created from this interface to submit the SQL statements to
the database. Some derived interfaces accept parameters in addition to executing stored
procedures.
ResultSet − These objects hold data retrieved from a database after you execute an SQL
query using Statement objects. It acts as an iterator to allow you to move through its
data.
SQLException − This class handles any errors that occur in a database application.
56
Figure 2.2 JDBC-ODBC Bridge Driver
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
57
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.
58
unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers
(written in Java language).
We can use JDBC API to handle database using Java program and can perform the following
activities:
o The basic use of SQL for data professionals and SQL users is to insert, update, and delete
the data from the relational database.
o SQL allows the data professionals and users to retrieve the data from the relational
database management systems.
o It also helps them to describe the structured data.
o It allows SQL users to create, drop, and manipulate the database and its tables.
o It also helps in creating the view, stored procedure, and functions in the relational
database.
o It allows you to define the data and modify that stored data in the relational database.
o It also allows SQL users to set the permissions or constraints on table columns, views,
and stored procedures.
Structured Query Language contains the following four components in its process:
o Query Dispatcher
o Optimization Engines
o Classic Query Engine
59
o SQL Query Engine, etc.
A classic query engine allows data professionals and users to maintain non-SQL queries. The
architecture of SQL is shown in the following diagram:
1. CREATE command : This command helps in creating the new database, new table, table
view, and other objects of the database.
2. UPDATE command : This command helps in updating or changing the stored data in the
database.
3. DELETE command : This command helps in removing or erasing the saved records from
the database tables. It erases single or multiple tuples from the tables of the database.
4. SELECT command : This command helps in accessing the single or multiple rows from
one or multiple tables of the database. We can also use this command with the WHERE
clause.
60
5. DROP command: This command helps in deleting the entire table, table view, and other
objects from the database.
6. INSERT command : This command helps in inserting the data or records into the
database tables. We can easily insert the records in single as well as multiple rows of the
table.
Advantages of SQL
Following are the best advantages or benefits of Structured Query Language:
1. No programming needed
SQL does not require a large number of coding lines for managing the database systems. We can
easily access and maintain the database by using simple SQL syntactical rules. These simple
rules make the SQL user-friendly.
A large amount of data is accessed quickly and efficiently from the database by using SQL
queries. Insertion, deletion, and updation operations on data are also performed in less time.
3. Standardized Language
SQL follows the long-established standards of ISO and ANSI, which offer a uniform
platform across the globe to all its users.
4. Portability
The structured query language can be easily used in desktop computers, laptops, tablets, and
even smartphones. It can also be used with other applications according to the user's
requirements.
5. Interactive language
We can easily learn and understand the SQL language. We can also use this language for
communicating with the database because it is a simple query language. This language is also
used for receiving the answers to complex queries in a few seconds.
The SQL language also helps in making the multiple views of the database structure for the
different database users.
Disadvantages of SQL
With the advantages of SQL, it also has some disadvantages, which are as follows:
61
1. Cost
The operation cost of some SQL versions is high. That's why some programmers cannot use the
Structured Query Language.
2. Interface is Complex
Another big disadvantage is that the interface of Structured query language is difficult, which
makes it difficult for SQL users to use and manage it.
The business rules are hidden. So, the data professionals and users who are using this query
language cannot have full database control.
The forName() method of Class class is used to register the driver class. This method is used to dynamically loa
the driver class.
1. Class.forName("oracle.jdbc.driver.OracleDriver");
62
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the database.
1Connection con=DriverManager.getConnection(
1. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
The createStatement() method of Connection interface is used to create statement. The object of statement
responsible to execute queries with the database.
Statement stmt=con.createStatement();
The executeQuery() method of Statement interface is used to execute queries to the database. This method return
the object of ResultSet that can be used to get all the records of a table.
63
Example to execute query
By closing connection object statement and ResultSet will be closed automatically. The close() method
Connection interface is used to close the connection.
con.close();
Example
// Java Program to Establish Connection in JDBC
// Importing database
importjava.sql.*;
// Importing required classes
importjava.util.*;
// Main class
class Main {
System.out.println("enter name");
String name = k.next();
System.out.println("enter class");
String cls = k.next();
// Registering drivers
DriverManager.registerDriver(
new oracle.jdbc.OracleDriver());
// Creating a statement
Statement st = con.createStatement();
// Executing query
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println(
"inserted successfully : " + sql);
else
System.out.println("insertion failed");
65
// Catch block to handle exceptions
catch (Exception ex) {
// Display message when exceptions occurs
System.err.println(ex);
}
}
}
Output:
// Class
class GFG {
66
// Try block to check if any exceptions occur
try {
67
e.printStackTrace();
}
}
}
Output:
2.Prepared Statement
Prepared Statement represents a recompiled SQL statement, that can be executed many
times. This accepts parameterized SQL queries. In this, “?” is used instead of the parameter,
one can pass the parameter dynamically by using the methods of PREPARED STATEMENT
at run time.
Example
// Java Program illustrating Prepared Statement in JDBC
// Main clas
class GFG {
69
System.out.println(e);
}
3.Callable Statement
Callable Statement are stored procedures which are a group of statements that we
compile in the database for some task, they are beneficial when we are dealing with
multiple tables with complex scenario & rather than sending multiple queries to the
database, we can send the required data to the stored procedure & lower the logic
executed in the database server itself. The Callable Statement interface provided by
JDBC API helps in executing stored procedures.
Syntax: To prepare a CallableStatement
CallableStatement cstmt = con.prepareCall("{call Procedure_name(?, ?}");
// Main class
class GFG {
70
// Step 3: Loading and registering drivers
CallableStatement cs
= con.prepareCall("{call peopleinfo(?,?)}");
cs.setString(1, "Bob");
cs.setInt(2, 64);
cs.execute();
ResultSet result
= s.executeQuery("select * from people");
71
// Print the line number where exception occurred
e.printStackTrace();
}
}
}
Output:
To execute a query, call an execute method from Statement such as the following:
execute: Returns true if the first object that the query returns is a ResultSet object. Use
this method if the query could return one or more ResultSet objects. Retrieve
the ResultSet objects returned from the query by repeatedly
calling Statement.getResultSet.
executeQuery: Returns one ResultSet object.
executeUpdate: Returns an integer representing the number of rows affected by the SQL
statement. Use this method if you are using INSERT, DELETE, or UPDATE SQL
statements.
2.10.2.1Scrollable ResultSet:
A scrollable ResultSet is one which allows us to retrieve the data in forward direction as well as
backward direction but no updations are allowed. In order to make the non-scrollable ResultSet
as scrollable ResultSet as scrollable ResultSet we must use the following createStatement which
is present in Connection interface.
72
Type represents type of scrollability and Mode represents either read only or updatable. The
value of Type and value of Mode are present in ResultSet interface as constant data members and
they are:
TYPE_FORWARD_ONLY - 1 CONCUR_READ_ONLY - 3
TYPE_SCROLL_INSENSITIVE - 2
Example Write a java program which illustrates the concept of Scrollable Result set?
import java.sql.*;
class ScrollResultSet {
73
rs.last();
System.out.println("LAST RECORD...");
System.out.println(rs.getInt(1) + " " + rs.getString(2));
rs.previous();
rs.relative(-1);
System.out.println("FIRST RECORD...");
System.out.println(rs.getInt(1) + " " + rs.getString(2));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}// main
};// ScrollResultSet
2.10.2.1 UpdateResultSet
Whenever we create a ResultSet object which never allows us to update the database through
ResultSet object and it allows retrieving the data only in forward direction. Such type of
ResultSet is known as non-updatable and non-scrollable ResultSet.
In order to make the ResultSet object as updatable and scrollable we must use the following
constants which are present in ResultSet interface.
TYPE_SCROLL_SENSITIVE CONCUR_UPDATABLE
The above two constants must be specified while we are creating Statement object by using the
following method:
For example: Write a java program which illustrates the concept of updatable ResultSet?
import java.sql.*;
74
class UpdateResultSet {
e.printStackTrace();
}
}// main
};// UpdateResultSet
75
JdbcRowSet
CachedRowSet
WebRowSet
FilteredRowSet
JoinRowSet
Example
// Java Program to Illustrate RowSet in JDBC
// Importing database
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
// Main class
class RowSetDemo {
76
// Creating a RowSet
JdbcRowSetrowSet = RowSetProvider.newFactory()
.createJdbcRowSet();
// Creating a query
rowSet.setCommand("select * from Student");
77
// Catch block to handle the exceptions
catch (Exception e) {
78