Code Documentation for Login Page
### 1. Class Definition
```java
public class Login extends javax.swing.JFrame {
```
The `Login` class extends `javax.swing.JFrame`, which means it is a Swing frame that will be used as a
window for the login interface.
### 2. Constructor
```java
public Login() {
initComponents();
setLocationRelativeTo(null);
}
```
The constructor initializes the components of the form by calling `initComponents()`, which is a method
automatically generated by the NetBeans GUI Builder. `setLocationRelativeTo(null)` centers the form on
the screen.
### 3. Initialization Method
```java
private void initComponents() {
// Component initialization code
}
```
`initComponents()` is an auto-generated method that sets up all the components (labels, text fields,
buttons, etc.) on the form. It includes layout settings and event listeners.
### 4. Event Listener Methods
#### `txtUsernameActionPerformed`
```java
private void txtUsernameActionPerformed(java.awt.event.ActionEvent evt) {
// No specific action defined here
}
```
This method is called when an action is performed on `txtUsername` (e.g., pressing Enter). Currently, it
does nothing but can be customized to add behavior if needed.
#### `jButton2ActionPerformed` (Exit Button)
```java
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
int a = JOptionPane.showConfirmDialog(null, "Are you sure you want to Exit?", "Select",
JOptionPane.YES_NO_OPTION);
if (a == 0) {
System.exit(0);
}
}
```
This method handles the event when the "Exit" button is clicked. It shows a confirmation dialog asking if
the user really wants to exit. If the user clicks "Yes" (value 0), the application terminates.
#### `jButton1ActionPerformed` (Login Button)
```java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String email = txtUsername.getText();
String password = txtPassword.getText();
int temp = 0;
try {
Connection con = ConnectionProvider.getCon();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM appuser1 WHERE email = '" + email + "' AND
password = '" + password + "' AND status = 'Active'");
while (rs.next()) {
temp = 1;
setVisible(false);
new Home(rs.getString("userRole")).setVisible(true);
}
if (temp == 0) {
JOptionPane.showMessageDialog(null, "Incorrect Email or Password");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
```
This method handles the event when the "Login" button is clicked. Here's a detailed breakdown of the
steps:
1. **Get User Input:**
- `String email = txtUsername.getText();`
- `String password = txtPassword.getText();`
- Retrieve the text entered by the user in the username and password fields.
2. **Initialize Temporary Variable:**
- `int temp = 0;`
- A temporary variable to track if a valid user is found.
3. **Database Connection:**
- `Connection con = ConnectionProvider.getCon();`
- Establish a connection to the database using `ConnectionProvider`.
4. **Create Statement:**
- `Statement st = con.createStatement();`
- Create a statement object to execute SQL queries.
5. **Execute Query:**
- `ResultSet rs = st.executeQuery("SELECT * FROM appuser1 WHERE email = '" + email + "' AND
password = '" + password + "' AND status = 'Active'");`
- Execute an SQL query to find a user with the provided email and password where the status is
'Active'.
6. **Process Result:**
- `while (rs.next()) { ... }`
- If a matching user is found, set `temp` to 1, hide the login form, and open the home page with the
user's role.
7. **Check Login Success:**
- `if (temp == 0) { JOptionPane.showMessageDialog(null, "Incorrect Email or Password"); }`
- If no matching user is found (`temp` remains 0), show an error message.
8. **Exception Handling:**
- `catch (Exception e) { JOptionPane.showMessageDialog(null, e); }`
- If an exception occurs (e.g., database connection issue), show the exception message.
### 5. Main Method
```java
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Login().setVisible(true);
}
});
}
```
The `main` method sets the look and feel of the UI to Nimbus if available and then launches the login
form by making it visible.
The provided Java code defines a graphical user interface (GUI) application for managing user accounts.
The application allows an admin to create, update, reset, and display user details. Below is a detailed
explanation of the code:
Code Documentation for Manage user Page
### Key Components
1. **Instance Variables**
- `appuserPk`: Stores the primary key of the selected user for updates.
- Various `javax.swing` components for the GUI: `JLabel`, `JTextField`, `JComboBox`, `JButton`,
`JTable`, and `JScrollPane`.
2. **Constructor**
- Initializes the GUI components and sets the frame location to the center of the screen.
3. **Validation Method**
- `validateFields(String formType)`: Checks if the required fields are filled based on the form type
("new" or "edit").
4. **initComponents Method**
- Initializes and configures the GUI components, setting their properties and adding them to the frame.
- Adds action listeners for the buttons and the table.
5. **Component Event Handlers**
- `formComponentShown`: Loads existing user data from the database when the form is shown.
- `txtNameActionPerformed`, `txtEmailActionPerformed`, `txtAddressActionPerformed`: Placeholder
methods for text field actions (currently not implemented).
- `comboBoxStatusActionPerformed`: Placeholder for combo box action (currently not implemented).
- `btnCloseActionPerformed`: Closes the form.
- `btnSaveActionPerformed`: Validates and saves a new user to the database.
- `btnUpdateActionPerformed`: Validates and updates an existing user in the database.
- `btnResetActionPerformed`: Resets the form and reloads the user list.
- `tableUserMouseClicked`: Populates the form fields with selected user details from the table.
6. **Main Method**
- Sets the look and feel of the application to "Nimbus" and creates an instance of `ManageUser` to
display the form.
### Detailed Component Functionality
#### Form Initialization and User Data Loading
- **`formComponentShown` Method:**
- Creates a `DefaultTableModel` for `tableUser`.
- Fetches user data from the database where the user role is "Admin" and populates the table with this
data.
- Disables the update button initially.
#### User Interaction Methods
- **Saving a New User (`btnSaveActionPerformed`):**
- Collects data from text fields and combo box.
- Validates the fields to ensure they are not empty.
- Inserts the new user data into the `appuser1` table in the database.
- Displays a success message and refreshes the form.
- **Updating an Existing User (`btnUpdateActionPerformed`):**
- Collects data from text fields and combo box.
- Validates the fields to ensure they are not empty (excluding password).
- Updates the selected user's data in the `appuser1` table in the database.
- Displays a success message and refreshes the form.
- **Resetting the Form (`btnResetActionPerformed`):**
- Resets the form by hiding and reopening it to clear fields and reload the user list.
- **Populating Fields from Table (`tableUserMouseClicked`):**
- Gets the selected row's user data and populates the form fields with this data.
- Sets the `appuserPk` to the selected user's primary key.
- Adjusts the status combo box to reflect the current status.
- Disables the password field and the save button, enables the update button.
#### Closing the Form
- **`btnCloseActionPerformed`:**
- Hides the form.
### Main Method
- Sets the Nimbus look and feel.
- Launches the `ManageUser` frame.
The provided code defines a Java Swing-based GUI application named `ManageCategory` that allows
users to manage categories in a database. Here is a detailed explanation of its functionality:
### Key Features
1. **Initialize Components**:
- The GUI components are initialized and laid out within the `initComponents` method.
- Components include labels, text fields, buttons, and a table for displaying category data.
2. **Display Categories**:
- When the form is shown (`formComponentShown` event), it connects to the database, retrieves all
categories, and displays them in the `tableCategory`.
3. **Add a New Category**:
- The user can enter a category name in the `txtName` text field and click the "Save" button.
- The `btnSaveActionPerformed` method validates the input and inserts a new category into the
database if the input is valid.
- After successfully adding a category, the form is reset to update the table with the new data.
4. **Update an Existing Category**:
- The user can select a category from the `tableCategory`, which populates the `txtName` text field with
the selected category's name.
- The `tableCategoryMouseClicked` method handles this functionality.
- The user can then modify the category name and click the "Update" button.
- The `btnUpdateActionPerformed` method validates the input and updates the category in the database
if the input is valid.
- After successfully updating a category, the form is reset to update the table with the modified data.
5. **Reset Form**:
- The "Reset" button clears all input fields and reloads the category table.
- The `btnResetActionPerformed` method handles this functionality by creating a new instance of
`ManageCategory` and displaying it.
6. **Close Application**:
- The "Close" button closes the application window.
- The `btnCloseActionPerformed` method sets the visibility of the form to false.
### Components
- **Labels**:
- `jLabel1`: Displays "Manage Category" as the title.
- `jLabel2`: Label for the `txtName` text field.
- **Text Field**:
- `txtName`: Input field for entering the category name.
- **Buttons**:
- `btnSave`: Triggers saving a new category.
- `btnUpdate`: Triggers updating an existing category.
- `btnReset`: Resets the form.
- `btnClose`: Closes the application window.
- **Table**:
- `tableCategory`: Displays the list of categories with columns "ID" and "Name".
- **Scroll Pane**:
- `jScrollPane1`: Provides scrolling functionality for `tableCategory`.
### Database Interaction
- **ConnectionProvider**: Assumed to be a utility class that provides a connection to the database.
- **SQL Queries**:
- Insert new category: `INSERT INTO category (name) VALUES (?)`
- Update existing category: `UPDATE category SET name = ? WHERE category_pk = ?`
- Select all categories: `SELECT * FROM category`
### Error Handling
- Validation errors (e.g., missing category name) are communicated to the user via `JOptionPane` dialog
boxes.
- Database errors (e.g., connection issues, SQL exceptions) are caught and displayed to the user via
`JOptionPane` dialog boxes.
### Summary
The `ManageCategory` application allows users to manage categories in a database through a user-
friendly GUI. Users can view, add, update, reset, and close the form, with all interactions resulting in real-
time updates to the database.
The provided code is a Java Swing application for managing product records in a database. It provides
functionality for adding, updating, and viewing products. Here’s a detailed breakdown of what the code
does:
### Key Components and Functions:
1. **Class Declaration and Variables**:
- The `ManageProduct` class extends `javax.swing.JFrame`, indicating it is a Swing-based GUI
application.
- `productPk` and `totalQuantity` are class-level variables to track the currently selected product and its
quantity.
2. **Constructor (`ManageProduct()`)**:
- Initializes the components and sets the window location to the center of the screen.
3. **getAllCategory() Method**:
- Retrieves all categories from the database and populates the `comboBoxCategory` dropdown.
4. **validateFields(String formType) Method**:
- Validates if required fields are filled in based on the form type ("new" or "edit").
5. **initComponents() Method**:
- Auto-generated code by NetBeans to initialize and configure the GUI components.
6. **Event Handlers**:
- `btnSaveActionPerformed`: Handles the save button click event to add a new product to the database.
- `btnUpdateActionPerformed`: Handles the update button click event to update an existing product in
the database.
- `btnCloseActionPerformed`: Handles the close button click event to close the application.
- `btnResetActionPerformed`: Handles the reset button click event to reset the form fields.
- `tableProductMouseClicked`: Handles the table row click event to load the selected product's details
into the form for editing.
- `formComponentShown`: Called when the form is shown; it retrieves and displays all categories and
products.
### Workflow:
1. **Form Initialization**:
- When the form is initialized (`new ManageProduct()`), it calls `initComponents()` to set up the UI.
- The `formComponentShown` event is triggered, calling `getAllCategory()` to populate the categories
and displaying all products in the `tableProduct`.
2. **Adding a New Product**:
- User enters product details (name, quantity, price, description) and selects a category.
- User clicks the "Save" button.
- The `btnSaveActionPerformed` method validates the input fields.
- If validation passes, it inserts the new product into the database.
3. **Updating an Existing Product**:
- User selects a product from the table.
- The `tableProductMouseClicked` method loads the product details into the form fields.
- User modifies the details and clicks the "Update" button.
- The `btnUpdateActionPerformed` method validates the input fields.
- If validation passes, it updates the product details in the database.
4. **Resetting the Form**:
- User clicks the "Reset" button.
- The `btnResetActionPerformed` method resets the form fields to their default state.
5. **Closing the Application**:
- User clicks the "Close" button.
- The `btnCloseActionPerformed` method closes the application window.
### GUI Components:
- **Labels**: Display text labels for the form fields.
- **Text Fields**: Input fields for product name, quantity, price, and description.
- **Buttons**: Trigger actions like save, update, reset, and close.
- **Combo Box**: Dropdown for selecting the product category.
- **Table**: Displays the list of products.
- **Scroll Pane**: Allows scrolling for the table when there are many products.
### Database Interaction:
- The code uses `ConnectionProvider.getCon()` to establish a database connection.
- SQL queries are executed to perform CRUD operations on the product records.
- **Insert**: Adds a new product.
- **Update**: Updates an existing product.
- **Select**: Retrieves categories and products to display in the UI.
### Error Handling:
- The code uses `JOptionPane` to display error messages for any exceptions encountered during database
operations.
In summary, the `ManageProduct` application provides a user interface for managing products, allowing
users to add new products, update existing ones, and view all products. It interacts with a database to store
and retrieve product data and handles various user actions through event handlers.