UNIT-11 (Java Application)
UNIT-11 (Java Application)
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.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
AWT Swing
AWT stands for “Abstract Windows Toolkit”. Swing is derived from Java Foundation Classes
(JFC).
AWT components are heavyweight Swing components are written on top of AWT
and as such the components are light-weight.
AWT components are part of the java.awt Swing components are part of javax.swing
package. package.
AWT Swing
AWT is platform - dependent. Swing components are written in Java and are
platform-independent.
AWT doesn’t have its look and feel. It adapts Swing provides a different look and feel of its
the look and feel of the platform on which it own.
runs.
AWT only has basic features and does not Swing provides advanced features like JTabbed
support advanced features like the table, tabbed panel, JTable, etc.
panel, etc.
AWT is as good as a thin layer of classes sitting Swing is larger and also contains rich
on top of the Operating system which makes it functionality.
platform-dependent.
AWT makes us write a lot of things. Swing has most of the features built-in.
Hierarchy of Java Swing classes
About JFrame:
Whenever you create a graphical user interface with Java Swing functionality, you will need a
container for your application. In the case of Swing, this container is called a JFrame. All GUI
applications require a JFrame. In fact some Applets even use a JFrame.
You can't build a house without a foundation. The same is true in Java: Without a container in
which to put all other elements, you won't have a GUI application. In other words, the JFrame is
required as the foundation or base container for all other graphical components.
A frame is actually a base window on which other components rely, namely the menu bar,
panels, labels, text fields, buttons, etc. Almost every other Swing application starts with the
JFrame window.
How to create a JFrame?
JFrame class has many constructors that are used to create a new JFrame. You can create a
JFrame using these methods:
We can write the code of swing inside the main(), constructor or any other method.
By creating the object of Frame class (association)
import javax.swing.*;
public class App {
public static void main(String[] args) throws Exception {
JFrame f=new JFrame();//creating instance of JFrame(associate)
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
}
}
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.
import javax.swing.*;
public class App {
App()
{
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
}
public static void main(String[] args) throws Exception {
new App();
}
}
2.Simple example of Swing by inheritance
We can also inherit the JFrame class, so there is no need to create the instance of JFrame class
explicitly.
import javax.swing.*;
public class App extends JFrame {
App()
{
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
add(b);//adding button on frame
setSize(400,500);
setLayout(null);
setVisible(true);
}
}
}
GUI Elements:
1. JLabel
2. JRadioButton
3. ButtonGroup
4. JCheckBox
5. JTextField
6. JTextArea
7. JButton
8. Border
9. JComboBox
10. JTabbedPane
11. JPasswordField
12. Look and Feel Management in Java Swing
1.JLabel
The object of the JLabel class may be a component for putting text in a container. It’s used to
display one line of read-only text. The text is often changed by an application but a user cannot
edit it directly. It inherits the JComponent class.
Syntax:
JLabel jl = new JLabel();
JLabel Constructors
JLabel(): It is used to create a JLabel instance with no image and with an empty string
for the title.
JLabel(String s): It is used to create a JLabel instance with the specified text.
JLabel(Icon i): It is used to create a JLabel instance with the specified image.
JLabel(String s, Icon I, int horizontalAlignment): It is used to create a JLabel instance
with the specified text, image, and horizontal alignment.
Exampl
e:
2.JRadioButton
This component allows the user to select only one item from a group item. By using the
JRadioButton component you can choose one option from multiple options.
Syntax: JRadioButton jrb = new JRadioButton();
JRadioButton Constructors
JRadioButton(): It is used to create an unselected radio button with no text.
JRadioButton(Label): It is used to create an unselected radio button with specified text.
JRadioButton(Label, boolean): It is used to create a radio button with the specified text
and selected status.
Code:
import javax.swing.*;
}
}
Output:
3.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.
Constructor Description
JPasswordField(int columns) Constructs a new empty JPasswordField with the specified number
of columns.
JPasswordField(String text) Constructs a new JPasswordField initialized with the specified text.
JPasswordField(String text, int Construct a new JPasswordField initialized with the specified text
columns) and columns.
Code:
import javax.swing.*;
}
}
Output:
4.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.
Constructor Description
JJCheckBox() Creates an initially unselected check box button with no text, no icon.
JCheckBox(Action a) Creates a check box where properties are taken from the Action supplied.
Code:
import javax.swing.*;
}
}
Output:
5. JComboBox
It inherits the JComponent class and is used to show pop up menu of choices.
import javax.swing.*;
}
}
Output:
6. 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
Commonly used Constructors:
Constructor Description
JTextArea(int row, int column) Creates a text area with the specified number of rows and columns
that displays no text initially.
JTextArea(String s, int row, int Creates a text area with the specified number of rows and columns
column) that displays specified text.
Code:
import javax.swing.*;
}
}
Output
Write a java program to create a GUI form as shown below
Code:
import javax.swing.*;
public class App {
public static void main(String[] args) throws Exception {
JFrame f=new JFrame();
JTextField nameField;
JTextArea addressArea;
JTextField emailField;
JRadioButton maleButton;
JRadioButton femaleButton;
JComboBox<String> countryComboBox;
JCheckBox hobbyReading;
JCheckBox hobbyTraveling;
JCheckBox hobbySports;
JButton submitButton;
f.setTitle("User Form");
// Create the components
JLabel nameLabel = new JLabel("Name:");
nameLabel.setBounds(20, 20, 100, 25);
nameField = new JTextField();
nameField.setBounds(140, 20, 200, 25);
f.add(nameLabel);
f.add(nameField);
f.setSize(400, 500);
f.setLayout(null);
f.setVisible(true);
}
}
Border Swing Control in Java
The border is an interface using which we can apply a border to every component. To create the
borders we have to use the methods available in BorderFactory class. We can apply the created
border to any component by using the SetBorder() method.
Syntax: Component.setBorder(Border);
Methods of Border
Border createLineBorder(Color, int): It is used to create a line border. Here, the Color
object specifies the color of the line and int specifies the width in pixels of the line.
Border createEtchedBorder(int, Color, Color): It is used to create an etched border.
Here, Color arguments specify the highlight and shadow colors to be used.
Here, int arguments allow the border methods to be specified as
either EtchedBorder.RAISED or EtchedBorder.LOWERED. The methods without
the int arguments create a lowered etched border.
Border createBevelBorder(int, Color, Color): It is used to create a raised or lowered
beveled border, specifying the colors to use. Here, the integer argument can be either
BevelBorder.RAISED or BevelBorder.LOWERED. Here, Color specifies the highlight
and shadow colors.
MatteBorder createMatteBorder(int, int, int, int, Icon): It is used to create a matte
border. Here, the integer arguments specify the number of pixels that the border occupies
at the top, left, bottom, and right (in that order) of whatever component uses it. Here, the
color argument specifies the color which with the border should fill its area. Here, the
icon argument specifies the icon which with the border should tile its area.
TitledBorder createTitledBorder(Border, String, int, int, Font, Color): Create a titled
border. Here, the string argument specifies the title to be displayed. Here, the optional
font and color arguments specify the font and color to be used for the title’s text. Here,
the border argument specifies the border that should be displayed along with the title.
Here, the integer arguments specify the number of pixels that the border occupies at the
top, left, bottom, and right (in that order) of whatever component uses it.
CompoundBorder createCompoundBorder(Border, Border): Combine two borders
into one. Here, the first argument specifies the outer border; the second, the inner border.
Code:
import javax.swing.*;
}
}
Output:
Layout Management:
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:
The Abstract Windowing Toolkit (AWT) has the following 3 layout managers:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
No Layout:
import javax.swing.*;
public class App extends JFrame{
JFrame f;
App()
{
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
Flow Layout:
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 panel.
Fields of FlowLayout class
public static final int LEFT(3)
public static final int RIGHT(2)
public static final int CENTER(1)
public static final int LEADING
public static final int TRAILING
Example:
import javax.swing.*;
import java.awt.*;
public class App{
JFrame f;
App()
{
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");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
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.add(b9); f.add(b10);
Output:
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
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
f=new JFrame();
// 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);
}
Output:
Grid Layout:
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
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
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:
import javax.swing.*;
import java.awt.*;
public class App{
JFrame f;
App()
{
f=new JFrame();
// creating 9 buttons
JButton btn1 = new JButton("1");
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");
f.add(btn1); f.add(btn2); f.add(btn3);
f.add(btn4); f.add(btn5); f.add(btn6);
f.add(btn7); f.add(btn8); f.add(btn9);
// setting the grid layout using the parameterless constructor
f.setLayout(new GridLayout());
f.setSize(300, 300);
f.setVisible(true);
}
Output:
Event Handling
An event is one of the most important concepts in Java. The change in the state of an object or behavior
by performing actions is referred to as an Event in Java. Actions include button click, keypress, page
scrolling, or cursor movement.
1. Foreground Events
2. Background Events
Foreground Events
Foreground events are those events that require user interaction to generate. In order to generate
these foreground events, the user interacts with components in GUI. When a user clicks on a button,
moves the cursor, and scrolls the scrollbar, an event will be fired.
Background Events
Background events don't require any user interaction. These events automatically generate in the
background. OS failure, OS interrupts, operation completion, etc., are examples of background events.
ActionListener:
The Java ActionListener is notified whenever you click on the button or menu item. It is notified against
ActionEvent. The ActionListener interface is found in java.awt.event package. It has only one method:
actionPerformed().
ActionListener Example:
import javax.swing.*;
import java.awt.event.*;
//1st Step Implement ActionListner
public class App implements ActionListener{
JTextField tf;
JButton b;
App()
{
JFrame f=new JFrame();
tf=new JTextField();
tf.setBounds(50,50, 150,20);
b=new JButton("Click Here");
b.setBounds(50,100,60,30);
//2nd step
b.addActionListener(this);
f.add(b);
f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
//3rd Step
public void actionPerformed(ActionEvent e)
{
tf.setText("Hello World");
}
public static void main(String[] args) throws Exception {
new App();
}
}
Output:
Lab: Write a java GUI Program to calculate square of entered number
Code:
import javax.swing.*;
import java.awt.event.*;
public class App implements ActionListener{
JTextField inputField;
JButton calculateButton;
JTextField outputField;
JFrame f=new JFrame();
public App()
{
f.setTitle("Square Calculator");
// Create the components
JLabel inputLabel = new JLabel("Enter any number:");
inputLabel.setBounds(20, 20, 200, 25);
inputField = new JTextField();
inputField.setBounds(200, 20, 150, 25);
f.add(inputLabel);
f.add(inputField);
f.setSize(400, 300);
f.setLayout(null);
f.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
int number = Integer.parseInt(inputField.getText());
int square = number * number;
outputField.setText(String.valueOf(square));
}
}
Lab: Write a java GUI Program to add two numbers from input fields and display sum in text
another textfield after clicking button calculate
import javax.swing.*;
import java.awt.event.*;
public class App implements ActionListener{
JTextField firstDigit;
JTextField secondDigit;
JButton calculateButton;
JTextField outputField;
JFrame f=new JFrame();
public App()
{
f.setTitle("Two Digit Calculator");
// Create the components
JLabel firstDigitLable = new JLabel("First Digit:");
firstDigitLable.setBounds(20, 20, 200, 25);
firstDigit = new JTextField();
firstDigit.setBounds(200, 20, 150, 25);
f.add(firstDigitLable);
f.add(firstDigit);
ItemListener:
The Java ItemListener is notified whenever you click on the checkbox. It is notified against ItemEvent.
The ItemListener interface is found in java.awt.event package. It has only one method:
itemStateChanged().
Eample:
import java.awt.*;
import java.awt.event.*;
public class App implements ItemListener{
Checkbox checkBox1,checkBox2;
Label label;
App()
{
Frame f=new Frame();
label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
checkBox1 = new Checkbox("C++");
checkBox1.setBounds(100,100, 50,50);
checkBox2 = new Checkbox("Java");
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
checkBox1.addItemListener(this);
checkBox2.addItemListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if(e.getSource()==checkBox1)
new App();
}
}
Output:
KeyListener:
The Java KeyListener is notified whenever you change the state of key. It is notified against KeyEvent.
The KeyListener interface is found in java.awt.event package. It has three methods.
1. keyPressed(KeyEvent e);
2. keyReleased(KeyEvent e);
3. keyTyped(KeyEvent e);
Example:
import java.awt.*;
import java.awt.event.*;
public class App implements KeyListener{
Label l;
TextArea area;
App()
{
Frame f=new Frame();
l = new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
f.add(l);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void keyPressed(KeyEvent e) {
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e) {
l.setText("Key Released");
}
public void keyTyped(KeyEvent e) {
l.setText("Key Typed");
}
public static void main(String[] args) throws Exception {
new App();
}
}
Output:
MouseListener:
The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods.
import java.awt.*;
import java.awt.event.*;
//1st Step Implement ActionListner
public class App implements MouseListener{
Label l;
App()
{
Frame f=new Frame();
l=new Label();
l.setBounds(20,50,100,20);
f.add(l);
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.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");
}
new App();
}
}
Output:
LAB: Write a GUI program using components to find sum and difference of two
numbers. Use two text fields for giving input and a label for output. The program should
display sum if user presses mouse and difference if user release mouse.
LAB: Write a GUI program using components to find sum and difference of two
numbers.Use two text fields for giving input and a label for output. The program should
display sum if user presses key and difference if user release key.
import javax.swing.*;
import java.awt.event.*;
public class App {
JLabel l1, l2, l3;
JTextField t1, t2, t3;
JFrame f = new JFrame("New Key Adapter");
App()
{
l1 = new JLabel("First Number:");
l1.setBounds(10,10,200,20);
t1 = new JTextField();
t1.setBounds(150,10,200,20);
l2 = new JLabel("Second Number:");
l2.setBounds(10,40,200,20);
t2 = new JTextField();
t2.setBounds(150,40,200,20);
l3 = new JLabel("Press any key");
l3.setBounds(10,70,200,20);
t3 = new JTextField();
t3.setBounds(150,70,200,20);
t3.addKeyListener(new checkkey());
f.add(l1); f.add(t1); f.add(l2); f.add(t2);f.add(l3);f.add(t3);
f.setSize(600,600);
f.setLayout(null);
f.setVisible(true);
}
class checkkey extends KeyAdapter{
public void keyPressed(KeyEvent e)
{
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
int sum = num1 + num2;
t3.setText(String.valueOf(sum));
}
}
MouseMotionListener:
The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified against
MouseEvent. The MouseMotionListener interface is found in java.awt.event package. It has two
methods.
1. mouseDragged(MouseEvent e);
2. mouseMoved(MouseEvent e);
MouseMotionListener Example:
import java.awt.*;
import java.awt.event.*;
public class App implements MouseMotionListener{
Frame f;
App()
{
f=new Frame();
f.addMouseMotionListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) throws Exception {
new App();
}
}
Output:
Lab: Write a Java program that displays a list of programming languages like(C#, Java, python,
php) using a JList. When the user selects an item and clicks a button, the selected language
should be displayed in a JLabel using swing.
}
}
Output:
Jpopup Menu
Code:
import javax.swing.*;
import java.awt.event.*;
f.add(popupmenu);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
Option Dialog:
JOptionPane class is used to display four types of dialog boxes
1. MessageDialog - dialog box that displays a message making it possible to add icons to
alert the user.
2. ConfirmDialog - dialog box that besides sending a message, enables the user to answer
a question.
3. InputDialog - dialog box that besides sending a message, allows entry of a text.
4. OptionDialog - dialog box that covers the three previous types.
Example:
import javax.swing.*;
public class App {
import javax.swing.*;
import java.awt.event.*;
}
Output:
File Chooser:
import javax.swing.JFileChooser;
In Java, developers can use the JTable method to create a table in their applications. JTable is a Swing
component that inherits from the JComponent class.
The adapter classes are found in java.awt.event, java.awt.dnd (drag and drop) and javax.swing.event
packages. The Adapter classes with their corresponding listener interfaces are given below.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
Example:
import java.awt.*;
import java.awt.event.*;
public class App{
Frame f;
App(){
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e) {
f.dispose();
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) throws Exception {
new App();
}
}