Wednesday, 15 October 2025

Exception Handling in PHP

Exception handling is a powerful mechanism in PHP, which is used to handle runtime errors (runtime errors are called exceptions). 

The main purpose of using exception handling is to maintain the normal execution of the application.

Exception

An exception is an unexpected outcome of a program, which can be handled by the program itself.

Basically, an exception disrupts the normal flow of the program. 

But it is different from an error because an exception can be handled, whereas an error cannot be handled by the program itself.


Need for Exception Handlers

Exception handling is required when an exception interrupts the normal execution of the program or application.

PHP provides a powerful mechanism for exception handling. 

It can be used to handle runtime errors such as IOException, SQLException, ClassNotFoundException, and more. 

A most popular example of exception handling is the divide by zero exception, which is an arithmetic exception.



Try block

The try block contains the code that may have an exception or where an exception can arise. 
When an exception occurs inside the try block during runtime of code, it is caught and resolved in catch block.
 The try block must be followed by a catch or finally block. 
A try block can be followed by minimum one and any number of catch blocks.

Catch block

The catch block contains the code that executes when a specified exception is thrown. 
It is always used with a try block, not alone. 
When an exception occurs, PHP finds the matching catch block.

Throw block

t is a keyword used to throw an exception. 
It also helps to list all the exceptions that a function throws but does not handle itself.
Remember that each throw must have at least one "catch".

Finally block
The finally block contains code, which is used for clean-up activity in PHP.
Basically, it executes the essential code of the program.

Exception outcome

The current state of the code is saved.
The execution of the code is switched to a predefined exception handler function.
Depending on the situation, 
  • the handler can halt the execution of the program, 
  • resume the execution from the saved code state, 
  • or continue the execution of the code from another location in the code.

//Script using Exception Handler

<?php  
//user-defined function with an exception  
function checkNumber($num) {  
   if($num>=1) {  
     //throw an exception  
     throw new Exception("Value must be less than 1");  
   }  
   return true;  
}  
  
//trigger an exception in a "try" block  
try {  
   checkNumber(5);  
   //If the exception throws, the below text will not be displayed  
   echo 'If you see this text, the passed value is less than 1';  
}  
  
//catch exception  
catch (Exception $e) {  
   echo 'Exception Message: ' .$e->getMessage();  
}  
?> 





Tuesday, 14 October 2025

Error handling in PHP

Errors

An error is a mistake in a program that may be caused by writing incorrect syntax or incorrect code. 

An error message is displayed in the browser 

The error message contains the filename along with the location, a message describing the error, and the line number at which the error has occurred.

Types of Errors

There are 12 unique error types, which can be grouped into 4 main categories:

  • Syntax Error or Parse Error
  • Informational (Notices)
  • Actionable (Warnings)
  • Fatal Errors

Syntax Error

It is also known as a Parse error.

These errors can occur due to common reasons like 

  • unclosed quotes, 
  • missing semicolon, 
  • extra or missing parentheses, 
  • or unclosed brackets and many more. 

While compiling the program, a syntax error can be caught by the compiler.

 It gives a parse error or syntax error message.

Syntax Error - Example

Example 1: Missing semicolon

<?php  
    /*---syntax error-------------------*/  
    echo "Alex: Hi! I'm Alex. </br>";  
    echo "Bob: I'm Bob. How are you?"  
    echo "Alex: I'm good! and you?";  
    echo "Bob: I'm also good";  
?>  
Parse error: syntax error, unexpected token "echo", expecting "," or ";" in C:\xampp\htdocs\Test\syntax.php on line 5


Fatal Errors

Something so terrible has happened during the execution of the script that further processing simply cannot continue.
It occurs when PHP cannot execute a critical operation, such as 
  • calling a non-existent function
  • including a missing file.
These stop the script execution immediately.

Fatal Error example

<?php
function add($x, $y) 
{
$sum = $x + $y;
echo "sum = " . $sum;
}
$x = 0;
$y = 20;
add($x, $y);
diff($x, $y);
?>
Fatal error: Uncaught Error: Call to undefined function diff() in C:\xampp\htdocs\Test\fatal.php:10 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Test\fatal.php on line 10

Actionable Errors (Warning Errors)

Non-fatal errors that allow the script to continue execution.
Example: Including a missing file or using an undefined variable.
Indicate that something clearly wrong has happened and that action should be taken.
e.g. file not present, database not available, missing function arguments, etc

Warning errors example

<?php
$x = "GeeksforGeeks";
include("gfg.php");
echo $x . " Computer science portal";
?>
Warning: include(gfg.php): Failed to open stream: No such file or directory in C:\xampp\htdocs\Test\warning.php on line 3

Informational(Notice) Errors

Same as a warning error.

Harmless problem that can be avoided through the use of explicit programming.

The warning error does not stop/prevent the execution of the program.
e.g. use of an undefined variable, defining a string without quotes, etc.

Notice errors example

<?php
$x = "Notice errors are deprecated";
echo $x;
echo $error;
?>
Warning: Undefined variable $error in C:\xampp\htdocs\Test\Notice.php on line 4

PHP Error Levels

There are 16 error levels in PHP. The 16 error levels are listed here:
  • E_ERROR: Fatal runtime errors.
  • E_WARNING: Runtime warnings (non-fatal errors).
  • E_PARSE: Compile-time parse errors.
  • E_NOTICE: Notices (non-critical runtime errors).
  • E_CORE_ERROR: Fatal errors during PHP's initial startup.
  • E_CORE_WARNING: Warnings during PHP's initial startup.
  • E_COMPILE_ERROR: Fatal compile-time errors.
  • E_COMPILE_WARNING: Compile-time warnings.
  • E_USER_ERROR: User-generated error messages.
  • E_USER_WARNING: User-generated warning messages.
  • E_USER_NOTICE: User-generated notice messages.
  • E_STRICT: Suggestions for improving code compatibility.
  • E_RECOVERABLE_ERROR: Catchable fatal errors.
  • E_DEPRECATED: Notices for deprecated code.
  • E_USER_DEPRECATED: User-generated deprecation warnings.
  • E_ALL: Represents all errors and warnings (except E_STRICT in older PHP versions).

Causing (Triggering) errors

It is possible to cause errors in PHP at any point in your script.
The trigger_error( ) function takes two parameters: 
  • the string output message to be printed out as the error 
  • and an optional second parameter of the type of error
trigger_error($msg,$type);
e.g.
if (!$db_conn) {
trigger_error(‘db conn failed’,E_USER_ERROR);
}

trigger_error( ) is better than just printing an error message and exiting the script
trigger_error( ) takes the form of PHP’s default errors
—it will automatically print out the filename and line number where the error occurred.
The second parameter affects how the script should react to the error. 
If the second parameter is not provided, the default is a user notice—a minor message that many people might not even see. 
However, any error type can be given as the second parameter, which can halt the execution of the script if the error is triggered.

Customising Error Handling

Generally, how PHP handles errors is defined by various constants in the installation (php.ini). 
1. Set error reporting settings
2. Suppressing Errors
3. Custom Error Handler

1. Set error reporting settings

error_reporting($level)
This function can be used to control which errors are displayed and which are simply ignored. 
The $level is an optional parameter 
The effect only lasts for the duration of the execution of your script. 

<?php
// Turn off all error reporting
error_reporting(0);


// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);


// Reporting E_NOTICE (to report uninitialized variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL ^ E_NOTICE);

// Report ALL PHP errors
error_reporting(E_ALL);
?> 

Note: Hiding errors is NOT a solution to a problem. 

2. Suppressing Errors

The special @ operator can be used to suppress function errors. 
Any error produced by the function is suppressed and not displayed by PHP, regardless of the error reporting setting

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any diagnostic error that might be generated by that expression will be suppressed.
<?php
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '" . error_get_last()['message'] . "'");
?>

Note: Error suppression is NOT a solution to a problem.
It can be useful to locally define your own error-handling mechanisms.
If you suppress any errors, you must check for them yourself elsewhere.

3. Custom Error Handler

function err_handler($errcode,$errmsg,$file,$lineno) 
{
echo ‘An error has occurred!<br />’;
         echo “file: $file<br />”;
        echo “line: $lineno<br />”;
        echo “Problem: $errmsg”;
return true;
}

The function then needs to be registered as your custom error handler:
set_error_handler(‘err_handler’);
You can ‘mask’ the custom error handler so it only receives certain types of errors. e.g. to register a custom handler just for user-triggered errors:
set_error_handler(‘err_handler’,E_USER_NOTICE | E_USER_WARNING | E_USER_ERROR);

A custom error handler is never passed E_PARSE, E_CORE_ERROR or E_COMPILE_ERROR errors as these are considered too dangerous.
Often used in conjunction with a ‘debug’ flag for a neat combination of debug and production code display..














 

PHP Study Material

Error handling in PHP


Exception Handling in PHP

SWING COMPONENTS

 The Swing components offer rich functionality and enable high-level customisation. The following components are described in this section.

  • JLabel
  • JTextField
  • JButton
  •  JToggleButton
  • JCheckBox
  • JRadioButton
  • JTabbedPane
  • JScrollPane
  • JList
  • JComboBox
  • JTree
  • JTable

JLabel

 JLabel is Swing’s easiest-to-use component.

JLabel can be used to display text and/or an icon.

 JLabel defines several constructors. Here are three of them: 

  •  JLabel(Icon icon) 
  •  JLabel(String str) 
  •  JLabel(String str, Icon icon, int align)

 The align argument specifies the horizontal alignment of the text and/or icon within the label. It must be one of the following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING.

The easiest way to obtain an icon is to use the ImageIcon class. An object of type ImageIcon can be passed as an argument to the Icon parameter of JLabel’s constructor.

Methods in JLabel

 The icon and text associated with the label can be obtained by the following methods: 
 Icon getIcon( ) 
 String getText( )

The icon and text associated with a label can be set by these methods: 
 void setIcon(Icon icon)
 void setText(String str)

Program using JLabel

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

public class MyFrame extends JFrame
{
JLabel l;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
l = new JLabel("This is a label!");
add(l);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

JTextField

 JTextField is the simplest and most widely used Swing text component. JTextField allows you to edit one line of text. It is derived from JTextComponent. Three of JTextField’s constructors are shown here: 
  •  JTextField(int cols)
  •  JTextField(String str, int cols) 
  •  JTextField(String str) 
 Here, str is the string to be initially presented, and cols is the number of columns in the text field. 
If no string is specified, the text field is initially empty.

Events handled in JTextField

ActionEvent - when the user presses the Enter key
 CaretEvent - each time the cursor changes position

Methods in JTextField

setText() - to display text
getText() - to retrieve text from the text field

Program using JTextField

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

public class MyFrame extends JFrame
{
JTextField jtf;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
jtf = new JTextField(20);
add(jtf);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Swing Buttons

Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and JRadioButton.
A button generates an action event when it is pressed. 

JButton

The JButton class provides the functionality of a push button. Three of its constructors are shown here: 
  •  JButton(Icon icon)
  •  JButton(String str) 
  •  JButton(String str, Icon icon) 
 When the button is pressed, an ActionEvent is generated.

getActionCommand()  - used to identify the button pressed when two or more buttons are present.

Program using JButton

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

public class MyFrame extends JFrame
{
JButton b;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
b = new JButton("Click Me");
add(b);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

JToggleButton

 A toggle button looks just like a push button, but it acts differently because it has two states: pushed and released. JToggleButton defines several constructors. The most commonly used one is:
 JToggleButton(String str)

JToggleButton generates an action event each time it is pressed. 
JToggleButton also generates an item event. 
  •  When a JToggleButton is pressed, it is selected. When it is popped out, it is deselected.
  • To handle ItemEvent, the ItemListener interface is implemented. This interface provides itemStateChanged() method. Inside itemStateChanged( ), 
getItem( ) - method can be used to identify the item selected.
isSelected() - used to check whether an item is selected or not.

Program using JToggleButton
import java.awt.*;
import javax.swing.*;

public class MyFrame extends JFrame
{
JToggleButton b;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
b = new JToggleButton("Click Me");
add(b);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

 Check Boxes

The JCheckBox class provides the functionality of a check box. JCheckBox defines several constructors. The one used here is
  • JCheckBox(String str) 
When the user selects or deselects a check box, an ItemEvent is generated.
A call to isSelected( ) determines if the box was selected or cleared. The getText( ) method gets the text for that check box.

Program using JCheckBox

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

public class MyFrame extends JFrame
{
JCheckBox c1;
JCheckBox c2;
JCheckBox c3;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
c1 = new JCheckBox("C");
c2 = new JCheckBox("C++");
c3 = new JCheckBox("Java");
add(c1);
add(c2);
add(c3);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Radio Buttons

 Radio buttons are a group of mutually exclusive buttons, where only one button can be selected at any time. They are supported by the JRadioButton class, which extends JToggleButton. JRadioButton provides several constructors.
 JRadioButton(String str)
 In order for their mutually exclusive nature to be activated, radio buttons must be configured into a group. Only one of the buttons in the group can be selected at any time. A button group is created by the ButtonGroup class.   Elements are then added to the button group via the following method: 
 void add(AbstractButton ab)

Methods
getActionCommand() - returns the label of the radio button
isSelected() - used to check whether a radio button is selected
getSource() - used to identify the radio button pressed

Program using JRadioButton

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

public class MyFrame extends JFrame
{
JRadioButton r1;
JRadioButton r2;
ButtonGroup bg;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
r1 = new JRadioButton("Male");
r2 = new JRadioButton("Female");
add(r1);
add(r2);
bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

 JTabbedPane

Tabbed panes are very common in the modern GUI.  It manages a set of components by linking them with tabs. Selecting a tab causes the component associated with that tab to come to the forefront. JTabbedPane defines three constructors. 
JTabbedPane()
JTabbedPane(int tabPlacement)

After creating a TabbedPane object, tabs are added using the following method:
 void addTab(String name, Component comp)

  The general procedure to use a tabbed pane is outlined here: 

  1.  Create an instance of JTabbedPane. 
  2.  Add each tab by calling addTab( ). 
  3.  Add the tabbed pane to the content pane

Program Using JTabbedPane

import java.awt.*;

import javax.swing.*;
public class MyFrame extends JFrame
{
JCheckBox c1;
JCheckBox c2;
JCheckBox c3;
JRadioButton r1;
JRadioButton r2;
ButtonGroup bg;
JLabel l;
JTextField jtf;
JPanel langs;
JPanel gender;
JPanel name;
JTabbedPane jtp;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
c1 = new JCheckBox("C");
c2 = new JCheckBox("C++");
c3 = new JCheckBox("Java");
langs = new JPanel();
langs.add(c1);
langs.add(c2);
langs.add(c3);
r1 = new JRadioButton("Male");
r2 = new JRadioButton("Female");
bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
gender = new JPanel();
gender.add(r1);
gender.add(r2);
l = new JLabel("Enter Name: ");
jtf = new JTextField(20);
name = new JPanel();
name.add(l);
name.add(jtf);
jtp = new JTabbedPane();
jtp.addTab("Languages", langs);
jtp.addTab("Gender", gender);
jtp.addTab("Name", name);
add(jtp);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

 JScrollPane

 JScrollPane is a lightweight container that automatically handles the scrolling of another component. The component being scrolled can be either an individual component or a group of components.  In either case, if the object being scrolled is larger than the viewable area, horizontal and/or vertical scroll bars are automatically provided.

The viewable area of a scroll pane is called the viewport. It is a window in which the component being scrolled is displayed. The scroll bars scroll the component through the viewport.  A JScrollPane will dynamically add or remove a scroll bar as needed.  JScrollPane defines several constructors. The simplest one is hown here: 

 JScrollPane(Component comp)

 Here are the steps to follow to use a scroll pane: 

  1.  Create the component to be scrolled. 
  2.  Create an instance of JScrollPane, passing to it the object to scroll. 
  3.  Add the scroll pane to the content pane

Program using JScrollPane

 import javax.swing.*;

public class JScrollPaneExample
{
    public static void main(String[] args)
    {
        // Create a JFrame
        JFrame frame = new JFrame("JScrollPane Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
 
        // Create a JTextArea
        JTextArea textArea = new JTextArea(10, 30);
        textArea.setText("This is a sample text.
                          \nYou can add more lines to see the scroll effect.
                          \nKeep typing to test scrolling!");
 
        // Wrap the JTextArea inside a JScrollPane
        JScrollPane scrollPane = new JScrollPane(textArea);
 
        // Add the JScrollPane to the frame
        frame.add(scrollPane);
         // Make the frame visible
        frame.setVisible(true);
    }
}

 JList

 In Swing, the basic list class is called JList. It supports the selection of one or more items from a list..

 JList provides several constructors. The one used here is 

  •  JList(E[ ] items)

 JList is based on two models. The first is ListModel. This interface defines how access to the list data is achieved. The second model is the ListSelectionModel interface, which defines methods that determine what list item or items are selected.

 A JList generates a ListSelectionEvent when the user makes or changes a selection.  It is handled by implementing ListSelectionListener. This listener specifies only one method, called valueChanged( ), 

By default, a JList allows the user to select multiple ranges of items within the list. The method

void setSelectionMode(int mode)

is used to change the selection mode. It must be one of these values defined by ListSelectionModel: SINGLE_SELECTION 

 SINGLE_INTERVAL_SELECTION 

 MULTIPLE_INTERVAL_SELECTION

Methods to get the selected items

 int getSelectedIndex( ) 

 Indexing begins at zero. So, if the first item is selected, this method will return 0. If no item is selected, –1 is returned.

 getSelectedValue( ) 

 It returns a reference to the first selected value. If no value has been selected, it returns null.


Program using JList

import java.awt.*;

import javax.swing.*;
public class MyFrame extends JFrame
{
JList<String> jl;
JScrollPane jsp;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
String[] branches = {"CSE", "ECE", "EEE", "IT", "MECH", "CIV"};
jl = new JList<String>(branches);
jsp = new JScrollPane(jl);
jsp.setPreferredSize(new Dimension(120, 80));
add(jsp);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

 JComboBox

A combo box (a combination of a text field and a drop-down list) 

A combo box displays one entry, but it will also display a drop-down list that allows a user to select a different entry. 

 The JComboBox constructor used by the example is shown here: 

 JComboBox(E[ ] items)

 Items can be dynamically added to the list of choices via the addItem( ) method, shown here: 

 void addItem(E obj)

JComboBox generates an 

action event when the user selects an item from the list. 

item event  - when the state of selection changes, which occurs when an item is selected or deselected.

getSelectedItem( ) -  to obtain the item selected in the list 

Program using JComboBox

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

public class MyFrame extends JFrame
{
JComboBox<String> jc;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
String[] branches = {"CSE", "ECE", "EEE", "IT", "MECH", "CIV"};
jc = new JComboBox<String>(branches);
add(jc);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Trees

 A tree is a component that presents a hierarchical view of data. Trees are implemented in Swing by the JTree class. A sampling of its constructors is shown here:
  •  JTree(Object[ ] obj) 
  •  JTree(Vector v) 
  •  JTree(TreeNode tn)

Although JTree is packaged in javax.swing, its support classes and interfaces are packaged in javax.swing.tree.

 JTree relies on two models: TreeModel and TreeSelectionModel.

Events generated

TreeExpansionEvent events occur when a node is expanded or collapsed. 

TreeSelectionEvent is generated when the user selects or deselects a node within the tree.

TreeModelEvent is fired when the data or structure of the tree changes. 

The listeners for these events are TreeExpansionListener, TreeSelectionListener, and TreeModelListener, respectively. The tree event classes and listener interfaces are packaged in javax.swing.event.

 Here are the steps to follow to use a tree:

  1.  Create an instance of JTree. 
  2.  Create a JScrollPane and specify the tree as the object to be scrolled.
  3.  Add the scroll pane to the content pane. 


Program using JTree

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

public class SimpleJTreeExample {
    public static void main(String[] args) {
        // Create the root node
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");

        // Add child nodes
        DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
        DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");
        root.add(child1);
        root.add(child2);

        // Add sub-child nodes
        child1.add(new DefaultMutableTreeNode("Sub-child 1.1"));
        child1.add(new DefaultMutableTreeNode("Sub-child 1.2"));
        child2.add(new DefaultMutableTreeNode("Sub-child 2.1"));

        // Create the JTree
        JTree tree = new JTree(root);

        // Add the tree to a scroll pane
        JScrollPane treeView = new JScrollPane(tree);

        // Create a JFrame to display the tree
        JFrame frame = new JFrame("Simple JTree Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(treeView);
        frame.setSize(300, 300);
        frame.setVisible(true);
    }
}

 JTable

 JTable is a component that displays rows and columns of data. It is also possible to select a row, column, or cell within the table, and to change the data within a cell.  JTable has many classes and interfaces associated with it. These are packaged in javax.swing.table. 

 JTable supplies several constructors. The one used here is 
  •  JTable(Object[ ][ ] data, Object[ ] colHeads). 
 Here, data is a two-dimensional array of the information to be presented, and colHeads is a one-dimensional array with the column headings.

 JTable relies on three models.
TableModel - defines those things related to displaying data in a two-dimensional format
TableColumnModel -  defines a table in terms of columns
ListSelectionModel - determines how items are selected in the table

 A JTable can generate several different events.
ListSelectionEvent is generated when the user selects something in the table
TableModelEvent is fired when that table’s data changes in some way

 Here are the steps required to set up a simple JTable that can be used to display data: 
 Create an instance of JTable. 
 Create a JScrollPane object, specifying the table as the object to scroll. 
 Add the scroll pane to the content pane.

Program using JTable

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

public class MyFrame extends JFrame
{
JTable jt;
JScrollPane jsp;
MyFrame()
{
setSize(500, 300);
setTitle("My Application");
setLayout(new FlowLayout());
String[] colHeads = {"Student", "JP", "FLAT", "CO"};
String[][] data = { {"Ramesh", "77", "80", "75"},
{"Suresh", "89", "86", "83"},
{"Mahesh", "74", "80", "75"},
{"Dinesh", "78", "80", "75"},
{"Gireesh", "89", "86", "83"},
{"Paramesh", "77", "84", "72"} };
jt = new JTable(data, colHeads);
jsp = new JScrollPane(jt);
jsp.setPreferredSize(new Dimension(450, 100));
add(jsp);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
MyFrame mf = new MyFrame();
}
}

Swings in Java

ORIGIN OF SWING 

  • The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but limited, graphical interface. 
  • The solution was Swing. Introduced in 1997,
  • Swing was included as part of the Java Foundation Classes (JFC). 
  • Swing was initially available for use with Java 1.1 as a separate library. 
  • However, beginning with Java 1.2, Swing (and the rest of the JFC) was fully integrated into Java.
  • The Java Swing tutorial is part of the Java Foundation Classes (JFC), which is used to create window-based applications.
  • It is built on top of the AWT (Abstract Windowing Toolkit) API and entirely written in Java. 
  • The javax.swing package provides classes for java swing API, such as JButton, JTextField, JTextArea, JRadioButton, JCheckBox, JMenu, JColorChooser, etc.

FEATURES OF SWINGS

  • Lightweight Components: 
    • The components created using the swings package don’t need the help of the native operating system.
    • Swings is part of Java Foundation Classes (JFC), which are purely developed in Java.
    • Swing components require fewer memory and CPU cycles than AWT components.
    • Hence, swing components are lightweight components.
  • Pluggable Look and Feel: 
    • Swings supports pluggable look and feel, i.e., the appearance of a component can be separated from the component's behaviour.
    • This enables programmers to assign different looks (themes) for the same component without changing its behaviour.

SWING VS AWT


MODEL VIEW CONTROLLER (MVC) ARCHITECTURE

  • Every GUI control or component contains three aspects:
    • The way the component looks (appearance) when rendered on the screen.
    • The way the component reacts to the user.
    • The state information associated with the component.
  • In MVC terminology, the model corresponds to the state information of a component.
    • For example, a button might contain a field that represents whether it is pressed or released.
  • The view corresponds to the look or appearance of the component when rendered on the screen.
    • For example, a button is displayed as a rectangle.
  • The controller determines how the component reacts to the user events.
    • For example, when the user presses a button, a new frame can be displayed.

MODEL-DELEGATE ARCHITECTURE

  • Swing uses a modified version of MVC that combines the view and the controller into a single logical entity called the UI delegate.
  • For this reason, Swing’s approach is called either the Model-Delegate architecture or the Separable Model architecture.
  • Swing’s pluggable look and feel is made possible by its Model-Delegate architecture.
  • To support the Model-Delegate architecture, most Swing components contain two objects.
    • The first represents the model.
    • The second represents the UI delegate.

COMPONENTS AND CONTAINERS

  • A Swing GUI consists of two key items: components and containers.
  • A component is an independent visual control, such as a push button or slider.
  • A container holds a group of components.
  • Thus, a container is a special type of component designed to hold other components.
  • For a component to be displayed, it must be held within a Container.
  • Thus, all Swing GUIs will have at least one container

COMPONENTS

  • Swing components are derived from the class JComponent (except the four top-level containers). 
  • JComponent supports pluggable look and feel and supports the functionality common to all components. 
  • JComponent class inherits the AWT classes Container and Component.
  • All of Swing’s components are represented by classes defined within the package javax.swing.

COMPONENTS IN SWINGS


CONTAINERS

  • Swing defines two types of containers.
  • The first are top-level containers: JFrame, JApplet, JWindow, and JDialog.
    • The top-level containers are heavyweight since they are inherited from the AWT classes Component and Container.
    • A top-level container is not contained within any other container.
    • The one most commonly used for applications is JFrame.
  • The second type of containers supported by Swing are lightweight containers.
    • Lightweight containers do inherit JComponent.
    • An example of a lightweight container is JPanel
    • In the past, the one used for applets was JApplet.

EVENT HANDLING IN SWINGS

  • The event handling mechanism used by Swing is the same as that used by the AWT.
  • This approach is called the delegation event model.
  • Swing uses the same events as does the AWT, and these events are packaged in java.awt.event.
  • Events specific to Swing are stored in javax.swing.event.

PAINTING IN SWING

  • To write output directly to the surface of a component, one or more drawing methods defined by the AWT, such as drawLine( ) or drawRect( ) must be used.
  • The AWT class Component defines a method called paint( ) that is used to draw output directly to the surface of a component.
  • Because JComponent inherits Component, all Swing’s lightweight components inherit the paint( ) method.
  • Swing uses three distinct methods: paintComponent( ), paintBorder( ), and paintChildren( ).
  • These methods paint the indicated portion of a component and divide the painting process into its three distinct, logical actions.
  • To paint to the surface of a Swing component, create a subclass of the component class and then override its paintComponent( ) method.

Simple Swing Program

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
  
class EventDemo 
{
   JLabel jlab; 
   EventDemo() 
  { 
      // Create a new JFrame container. 
      JFrame jfrm = new JFrame("An Event Example"); 

     // Specify FlowLayout for the layout manager. 
      jfrm.setLayout(new FlowLayout()); 
 
    // Give the frame an initial size. 
    jfrm.setSize(720, 690); 
 
    // Terminate the program when the close button is pressed        
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
 
    // Make three buttons. 
    JButton b1 = new JButton("RED"); 
    JButton b2 = new JButton("BLUE"); 
    JButton b3 = new JButton("GREEN");
 
      // Add action listener for red. 
     b1.addActionListener(new ActionListener() 
     { 
        public void actionPerformed(ActionEvent ae) 
       { 
          jfrm.getContentPane().setBackground(Color.red);
       } 
    }); 
 
    // Add action listener for blue. 
    b2.addActionListener(new ActionListener() 
    { 
      public void actionPerformed(ActionEvent ae) 
      { 
        jfrm.getContentPane().setBackground(Color.blue);
      } 
    }); 

    //Add action listener for green
    b3.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent ae)
      {
              jfrm.getContentPane().setBackground(Color.green);
     }
  });

    // Add the buttons to the content pane. 
    jfrm.add(b1);  
    jfrm.add(b2); 
    jfrm.add(b3); 
 
    // Create a text-based label. 
    JLabel jlab = new JLabel("Press a button."); 
 
    // Add the label to the content pane. 
    jfrm.add(jlab); 
 
    // Display the frame. 
    jfrm.setVisible(true); 
  } 
 
  public static void main(String args[]) 
  { 
    SwingUtilities.invokeLater(new Runnable() 
    { 
      public void run() 
      { 
        new EventDemo(); 
      } 
    }); 
  } 
}