Wednesday 3 January 2024

Unit 6: introducing swing and java database connectivity(JDBC) | Java Programming | ICT. Ed 455 | BICTE | Fifth Semester | Bicte blog

 

Unit 6: introducing swing and java database connectivity(JDBC)                            8+12

6.1 Design philosophy of swing

6.2 Components and Containers

6.3 Layout Managers

6.4 Swing event handling

6.5 Basic swing components: JButton, JTextField, JCheckBox, JList

6.6 Use Anonymous Inner Classes to Handle Events

What is Swing in Java?

Swing in Java is a Graphical User Interface (GUI) toolkit that includes the GUI components. Swing provides a rich set of widgets and packages to make sophisticated GUI components for Java applications. Swing is a part of Java Foundation Classes(JFC), which is an API for Java GUI programing that provide GUI.

The Java Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older, platform dependent GUI toolkit. You can use the Java simple GUI programming components like button, textbox, etc., from the library and do not have to create the components from scratch.

Java Swing class Hierarchy Diagram




Swing Class Hierarchy Diagram

All components in Java Swing are JComponent which can be added to container classes.

 

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database. There are four types of JDBC drivers:

  • JDBC-ODBC Bridge Driver,
  • Native Driver,
  • Network Protocol Driver, and
  • Thin Driver

We have discussed the above four drivers in the next chapter.

We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API, we can save, update, delete and fetch data from the database. It is like Open Database Connectivity (ODBC) provided by Microsoft.


The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based on the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces for JDBC API. A list of popular interfaces of JDBC API are given below:

  • Driver interface
  • Connection interface
  • Statement interface
  • PreparedStatement interface
  • CallableStatement interface
  • ResultSet interface
  • ResultSetMetaData interface
  • DatabaseMetaData interface
  • RowSet interface

A list of popular classes of JDBC API are given below:

  • DriverManager class
  • Blob class
  • Clob class
  • Types class

Why Should We Use JDBC

Before JDBC, ODBC API was the database API to connect and execute the query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and 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:

  1. Connect to the database
  2. Execute queries and update statements to the database
  3. Retrieve the result received from the database.

Components

Components, in Java, refer to the basic elements that form the user interface. These elements are responsible for rendering specific functionalities or features on the screen. Common examples of components include buttons, labels, text fields, checkboxes, radio buttons, sliders, and more. Each component represents a specific user interface control with specific behaviors and attributes. Components can be interactive or non-interactive, depending on their nature.

Key characteristics of components include:

  • Visual Representation: Components have a visual representation on the screen and can be seen and interacted with by users.
  • Events and Listeners: Components can generate events when certain actions occur (e.g., button click, text input), and developers can attach event listeners to respond to these events.
  • Customizability: Components often have customizable properties, such as size, color, font, and alignment, which allow developers to tailor their appearance.
  • Reusability: Components are designed to be reusable, making it easy to include the same or similar elements across multiple parts of an application.
  • Hierarchical: Components can be combined in a hierarchical structure, allowing complex UI layouts.

Containers

Containers, on the other hand, are components that serve as a holding space for other components. In essence, containers are responsible for organizing and managing the layout of their child components. They provide structure and help create complex UI designs by defining how components are positioned and displayed within them.

Key characteristics of containers include:

  • Nested Structure: Containers can contain other containers, forming a nested structure that enables the creation of intricate UI layouts.
  • Layout Management: Containers utilize layout managers to define the rules for arranging their child components. Layout managers determine the positioning and sizing of components within the container, ensuring consistent appearance across different screen sizes and resolutions.
  • No Direct User Interaction: Unlike regular components, containers are not meant to be interacted with directly by users. They are more of an organizational tool for other components.
  • Swing and AWT: In Java, containers are mainly associated with AWT (Abstract Window Toolkit) and Swing, the two standard GUI libraries. AWT containers include classes like Frame, Panel, and Window, while Swing containers are represented by classes like JFrame, JPanel, and JWindow.

 

LayoutManagers

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.

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

Constructors of BorderLayout class:

  • BorderLayout(): creates a border layout but with no gaps between the components.
  • 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

  1. import java.awt.*;    
  2. import javax.swing.*;    
  3.     
  4. public class Border   
  5. {    
  6. JFrame f;    
  7. Border()  
  8. {    
  9.     f = new JFrame();    
  10.         
  11.      // creating buttons  
  12.     JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH   
  13.     JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH  
  14.     JButton b3 = new JButton("EAST");; // the button will be labeled as EAST  
  15.     JButton b4 = new JButton("WEST");; // the button will be labeled as WEST  
  16.     JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER  
  17.         
  18.     f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction    
  19.     f.add(b2, BorderLayout.SOUTH);  // b2 will be placed in the South Direction    
  20.     f.add(b3, BorderLayout.EAST);  // b2 will be placed in the East Direction    
  21.     f.add(b4, BorderLayout.WEST);  // b2 will be placed in the West Direction    
  22.     f.add(b5, BorderLayout.CENTER);  // b2 will be placed in the Center    
  23.         
  24.     f.setSize(300, 300);    
  25.     f.setVisible(true);    
  26. }    
  27. public static void main(String[] args) {    
  28.     new Border();    
  29. }    
  30. }    

Output:


Event and Listener (Java Event Handling)

Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event package provides many event classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces

Event Classes

Listener Interfaces

ActionEvent

ActionListener

MouseEvent

MouseListener and MouseMotionListener

MouseWheelEvent

MouseWheelListener

KeyEvent

KeyListener

ItemEvent

ItemListener

TextEvent

TextListener

AdjustmentEvent

AdjustmentListener

WindowEvent

WindowListener

ComponentEvent

ComponentListener

ContainerEvent

ContainerListener

FocusEvent

FocusListener

Steps to perform Event Handling

Following steps are required to perform event handling:

  1. Register the component with the Listener

Registration Methods

For registering the component with the Listener, many classes provide the registration methods. For example:

  • Button
    • public void addActionListener(ActionListener a){}
  • MenuItem
    • public void addActionListener(ActionListener a){}
  • TextField
    • public void addActionListener(ActionListener a){}
    • public void addTextListener(TextListener a){}
  • TextArea
    • public void addTextListener(TextListener a){}
  • Checkbox
    • public void addItemListener(ItemListener a){}
  • Choice
    • public void addItemListener(ItemListener a){}
  • List
    • public void addActionListener(ActionListener a){}
    • public void addItemListener(ItemListener a){}

Java Event Handling Code

We can put the event handling code into one of the following places:

  1. Within class
  2. Other class
  3. Anonymous class

Java event handling by implementing ActionListener

  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. class AEvent extends Frame implements ActionListener{  
  4. TextField tf;  
  5. AEvent(){  
  6.   
  7. //create components  
  8. tf=new TextField();  
  9. tf.setBounds(60,50,170,20);  
  10. Button b=new Button("click me");  
  11. b.setBounds(100,120,80,30);  
  12.   
  13. //register listener  
  14. b.addActionListener(this);//passing current instance  
  15.   
  16. //add components and set size, layout and visibility  
  17. add(b);add(tf);  
  18. setSize(300,300);  
  19. setLayout(null);  
  20. setVisible(true);  
  21. }  
  22. public void actionPerformed(ActionEvent e){  
  23. tf.setText("Welcome");  
  24. }  
  25. public static void main(String args[]){  
  26. new AEvent();  
  27. }  
  28. }  

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example that sets the position of the component it may be button, textfield etc.


2) Java event handling by outer class

  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. class AEvent2 extends Frame{  
  4. TextField tf;  
  5. AEvent2(){  
  6. //create components  
  7. tf=new TextField();  
  8. tf.setBounds(60,50,170,20);  
  9. Button b=new Button("click me");  
  10. b.setBounds(100,120,80,30);  
  11. //register listener  
  12. Outer o=new Outer(this);  
  13. b.addActionListener(o);//passing outer class instance  
  14. //add components and set size, layout and visibility  
  15. add(b);add(tf);  
  16. setSize(300,300);  
  17. setLayout(null);  
  18. setVisible(true);  
  19. }  
  20. public static void main(String args[]){  
  21. new AEvent2();  
  22. }  
  23. }  
  1. import java.awt.event.*;  
  2. class Outer implements ActionListener{  
  3. AEvent2 obj;  
  4. Outer(AEvent2 obj){  
  5. this.obj=obj;  
  6. }  
  7. public void actionPerformed(ActionEvent e){  
  8. obj.tf.setText("welcome");  
  9. }  
  10. }  

3) Java event handling by anonymous class

  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. class AEvent3 extends Frame{  
  4. TextField tf;  
  5. AEvent3(){  
  6. tf=new TextField();  
  7. tf.setBounds(60,50,170,20);  
  8. Button b=new Button("click me");  
  9. b.setBounds(50,120,80,30);  
  10.   
  11. b.addActionListener(new ActionListener(){  
  12. public void actionPerformed(){  
  13. tf.setText("hello");  
  14. }  
  15. });  
  16. add(b);add(tf);  
  17. setSize(300,300);  
  18. setLayout(null);  
  19. setVisible(true);  
  20. }  
  21. public static void main(String args[]){  
  22. new AEvent3();  
  23. }  
  24. }  

What is Java Swing?

Java Swing is a popular and powerful Graphical User Interface (GUI) toolkit that is used for developing desktop applications. It is a part of the Java Foundation Classes (JFC) and provides a rich set of components and layout managers for creating a variety of GUIs. Java Swing is platform-independent and can be used on any operating system that supports Java.

It provides a set of lightweight components that are not only easy to use but also customizable. Some of the commonly used components in Swing are buttons, text fields, labels, menus, and many more.

Java Swing provides a pluggable look and feels that allows developers to customize the GUI according to the user’s preferences. It also provides a robust event-handling mechanism that allows developers to handle events generated by the graphical components.

Some of the commonly used layout managers in Java Swing are BorderLayout, FlowLayout, GridLayout, CardLayout, and BoxLayout. These layout managers allow developers to create complex and intuitive GUIs that are easy to use and navigate.

Java Swing Class Hierarchy

The Java Swing API hierarchy is shown below:



Java Swing Packages

Some of the commonly used packages in Java Swing are:

  1. javax.swing: This package contains the core components of Swing, such as JButton, JLabel, JTable, JList, and many more. It also contains the classes for creating top-level containers such as JFrame and JDialog.
  2. javax.swing.event: This package contains the classes for handling events generated by the Swing components. It includes event listener interfaces, event adapter classes, and event objects.
  3. javax.swing.border: This package contains classes for creating borders around the Swing components. It includes the classes for creating line borders, etched borders, and titled borders.
  4. javax.swing.layout: This package contains the classes for creating and managing layout managers in Swing. It includes the commonly used layout managers such as BorderLayout, FlowLayout, GridLayout, BoxLayout, and CardLayout.
  5. javax.swing.plaf: This package contains the classes for the pluggable look and feels feature of Swing. It includes the classes for creating and managing the look and feel themes, and also provides the default look and feel theme for each platform.
  6. javax.swing.text: This package contains the classes for creating and managing text components in Swing. It includes classes for creating text fields, text areas, and other text-related components.
  7. javax.swing.table: This package contains the classes for creating and managing tables in Swing. It includes the classes for creating JTable, TableModel, TableColumn, and TableCellRenderer.

Components of Java Swing

Some of the important and common components of the Java Swing class are:

  1. JFrame: JFrame is a top-level container that represents the main window of a GUI application. It provides a title bar, and minimizes, maximizes, and closes buttons.
  2. JPanel: JPanel is a container that can hold other components. It is commonly used to group related components together.
  3. JButton: JButton is a component that represents a clickable button. It is commonly used to trigger actions in a GUI application.
  4. JLabel: JLabel is a component that displays text or an image. It is commonly used to provide information or to label other components.
  5. JTextField: JTextField is a component that allows the user to input text. It is commonly used to get input from the user, such as a name or an address.
  6. JCheckBox: JCheckBox is a component that represents a checkbox. It is commonly used to get a binary input from the user, such as whether or not to enable a feature.
  7. JList: JList is a component that represents a list of elements. It is typically used to display a list of options from which the user can select one or more items.
  8. JTable: JTable is a component that represents a data table. It is typically used to present data in a tabular fashion, such as a list of products or a list of orders.
  9. JScrollPane: JScrollPane is a component that provides scrolling functionality to other components. It is commonly used to add scrolling to a panel or a table.

Java Anonymous inner class

Java anonymous inner class is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain "extras" such as overloading methods of a class or interface, without having to actually subclass a class.

In simple words, a class that has no name is known as an anonymous inner class in Java. It should be used if you have to override a method of class or interface. Java Anonymous inner class can be created in two ways:

  1. Class (may be abstract or concrete).
  2. Interface

Java anonymous inner class example using class

TestAnonymousInner.java

  1. abstract class Person{  
  2.   abstract void eat();  
  3. }  
  4. class TestAnonymousInner{  
  5.  public static void main(String args[]){  
  6.   Person p=new Person(){  
  7.   void eat(){System.out.println("nice fruits");}  
  8.   };  
  9.   p.eat();  
  10.  }  
  11. }  

Test it Now

Output:

nice fruits

Internal working of given code

  1. Person p=new Person(){  
  2. void eat(){System.out.println("nice fruits");}  
  3. };  
  1. A class is created, but its name is decided by the compiler, which extends the Person class and provides the implementation of the eat() method.
  2. An object of the Anonymous class is created that is referred to by 'p,' a reference variable of Person type.

Internal class generated by the compiler

  1. import java.io.PrintStream;  
  2. static class TestAnonymousInner$1 extends Person  
  3. {  
  4.    TestAnonymousInner$1(){}  
  5.    void eat()  
  6.     {  
  7.         System.out.println("nice fruits");  
  8.     }  
  9. }  

Java anonymous inner class example using interface

  1. interface Eatable{  
  2.  void eat();  
  3. }  
  4. class TestAnnonymousInner1{  
  5.  public static void main(String args[]){  
  6.  Eatable e=new Eatable(){  
  7.   public void eat(){System.out.println("nice fruits");}  
  8.  };  
  9.  e.eat();  
  10.  }  
  11. }  

Test it Now

Output:

nice fruits

Internal working of given code

It performs two main tasks behind this code:

  1. Eatable p=new Eatable(){  
  2. void eat(){System.out.println("nice fruits");}  
  3. };  
  1. A class is created, but its name is decided by the compiler, which implements the Eatable interface and provides the implementation of the eat() method.
  2. An object of the Anonymous class is created that is referred to by 'p', a reference variable of the Eatable type.

Internal class generated by the compiler

  1. import java.io.PrintStream;  
  2. static class TestAnonymousInner1$1 implements Eatable  
  3. {  
  4. TestAnonymousInner1$1(){}  
  5. void eat(){System.out.println("nice fruits");}  
  6. }  

 



No comments:

Post a Comment