Java - JTable with Gradient Background

How to Customize JTable Background with Gradient Colors In Java Netbeans

JTable with Gradient Background


In this Java Tutorial we will see How To Create a JTable with a gradient background In Java Using Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:


package new_tutorials;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Point2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.plaf.basic.BasicTableUI;

/**
 *
 * @author 1BestCsharp
 */
public class GradientBackgroundTable extends JFrame{

    public GradientBackgroundTable(){
        
        setTitle("Gradient Background Table");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String[] columnNames = {"Column 1","Column 2","Column 3"};
        Object[][] data = {
            {"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},
            {"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},
            {"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},
            {"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},{"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},{"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},{"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},{"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},{"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},{"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},{"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},
            {"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},
            {"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},
            {"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},{"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},{"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},{"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},{"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},{"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"},{"Data 1", "Data 2", "Data 3"},
            {"Data 4", "Data 5", "Data 6"}
        };
        JTable table = new JTable(data,columnNames);
        table.setUI(new GradientTableUI());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
        setSize(400,300);
        setLocationRelativeTo(null);
        
    }
    
    public static void main(String[] args) {
        GradientBackgroundTable frame = new GradientBackgroundTable();
        frame.setVisible(true);
    }
    
    
}


class GradientTableUI extends BasicTableUI{
    
    @Override
    public void paint(Graphics g, JComponent c){
        JTable gTable = (JTable)c;
        Graphics2D g2d = (Graphics2D) g;
        
        // Create a gradient paint for the background
        Point2D startPoint = new Point2D.Float(0, 0);
        Point2D endPoint = new Point2D.Float(0, gTable.getHeight());
        Color color1 = Color.green;
        Color color2 = Color.red;
        GradientPaint gradientPaint = new GradientPaint(startPoint, color1, endPoint, color2);
        
        // Set the gradient paint and fill the entire background
        g2d.setPaint(gradientPaint);
        g2d.fillRect(0, 0, gTable.getWidth(), gTable.getHeight());
        // Paint the rest of the table components
        super.paint(g2d, c);

    }
    
}



The Final Result:

Java JTable with Gradient Background 1

Java JTable with Gradient Background 2

Java JTable with Gradient Background 3










JavaScript - Create Pagination Button For HTML Table

How to Add Pagination to HTML Tables Using JavaScript


JavaScript Create Pagination Button For HTML Table



In this Javascript tutorial, we will see how to create pagination buttons for HTML table with JavaScript. 
This JavaScript code adds pagination functionality to a table of product data, allowing users to navigate through multiple pages of data. It dynamically generates page navigation buttons and shows the relevant rows based on the selected page.



Project Source Code:



<!DOCTYPE html>
<html>
<head>
<title>Pagination</title>
<style>
table{width: 25%; border: 1px solid #555}

table tr{border: 1px solid #555}

table td{border: 1px solid #555}

.page-nav{background-color: yellowgreen; width: 25%; display: flex;
flex-wrap: wrap; justify-content: center}

.page-nav button{background-color: #333; color: #fff;}

.page-nav button:hover{background-color: rgb(119, 16, 16); color: #fff;
cursor: pointer;}

</style>
</head>
<body>
<table id="table">
<thead>
<tr>
<th>Product</th>
<th>Stock</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Product 1</td>
<td>10</td>
<td>$11</td>
</tr>
<tr>
<td>Product 2</td>
<td>20</td>
<td>$331</td>
</tr>
<tr>
<td>Product 3</td>
<td>25</td>
<td>$14</td>
</tr>
<tr>
<td>Product 4</td>
<td>99</td>
<td>$73</td>
</tr>
<tr>
<td>Product 5</td>
<td>14</td>
<td>$30</td>
</tr>
<tr>
<td>Product 6</td>
<td>44</td>
<td>$22</td>
</tr>
<tr>
<td>Product 7</td>
<td>77</td>
<td>$33</td>
</tr>
<tr>
<td>Product 8</td>
<td>57</td>
<td>$62</td>
</tr>
<tr>
<td>Product 9</td>
<td>76</td>
<td>$59</td>
</tr>
<tr>
<td>Product 10</td>
<td>27</td>
<td>$42</td>
</tr>
<tr>
<td>Product 11</td>
<td>151</td>
<td>$36</td>
</tr>
<tr>
<td>Product 12</td>
<td>96</td>
<td>$80</td>
</tr>
<tr>
<td>Product 13</td>
<td>85</td>
<td>$32</td>
</tr>
<tr>
<td>Product 14</td>
<td>35</td>
<td>$75</td>
</tr>
</tbody>
</table>


<script>

// select the table and its rows
const table = document.getElementById('table');
const rows = table.querySelectorAll('tbody tr');

// set the number of rows per page and initialize the current page to 1
const rowsPerPage = 5;
let currentPage = 1;

// create a new div to hold the page navigation buttons
const pageNav = document.createElement('div');
pageNav.classList.add('page-nav');
table.parentNode.insertBefore(pageNav, table.nextSibling);


// function to show the rows of the current page
const showPage = (page)=>{
// set the current page to the one specified
currentPage = page;

// calculate the start and end indexes of the rows to display
const startIndex = (page - 1) * rowsPerPage;
const endIndex = startIndex + rowsPerPage;

// hide all rows
for(let i = 0; i < rows.length; i++){
rows[i].style.display = "none";
}

// display the rows within the selected range
for(let i = startIndex; i < endIndex; i++){
if(rows[i]){
rows[i].style.display = "table-row";
}
}

// update the current page button
const buttons = document.querySelectorAll(".page-nav button");
for(let i = 0; i < buttons.length; i++){
buttons[i].classList.remove("current-page");
}
// if the table is not empty
if(rows.length > 0)
{
document.querySelector(`#page-${currentPage}`).classList.add("current-page");
}

}


// function to create the page buttons
const createPageButtons = () => {
// calculate the total number of pages
const pages = Math.ceil(rows.length / rowsPerPage);
// create a button for each page
for(let i = 1; i <= pages; i++)
{
const button = document.createElement("button");
// set the ID of the button to "page-x", where x is the page number
button.id = `page-${i}`;
// set the button text to the page number
button.textContent = i;
// set the class of the first button to "current-page"
if(i === 1)
{
button.classList.add("current-page");
}
// add an event listener to the button that calls showPage()
// with the corresponding page number
button.addEventListener("click",() => {
showPage(i);
});
// append the button to the page navigation div
pageNav.appendChild(button);
}
}

// call createPageButtons() to create the initial set of page buttons
createPageButtons();
// call showPage() with an argument of 1 to display the first page of rows
showPage(1);

</script>

</body>
</html>






Code Explanation:

this JavaScript code, allows users to create a table with pagination.

This JavaScript code performs the following actions:

1 - Select Table Rows: Choose the table with the ID "table" and select all its rows in the tbody.

2 - Pagination Setup: Specify the number of rows per page (rowsPerPage) and start on page 1.

3 - Create Page Navigation: Generate a new <div> for page navigation buttons below the table. 
Define a function to make these buttons.

4 - Show Page Function: Create a function to show rows for the current page. 
Calculate start and end indexes. 
Hide all rows and show the selected range. 
Update the "current-page" class for the navigation button.

5 - Generate Page Buttons: Calculate total pages based on rows and rows per page. 
Make buttons for each page. 
Set button IDs to "page-x," where x is the page number. 
Add event listeners to call showPage for each page. 
Append buttons to the navigation div.



OUTPUT:





PHP Calculator Source Code

How To Create A Calculator In PHP



In this php tutorial, we will see how to create a simple web-based calculator using PHP and JavaScript.
This application allow users to do Basic Operations (+, -, /, *, √, ^):

Addition (+): It can add two numbers together.
Subtraction (-): It can subtract one number from another.
Multiplication (*): It can multiply two numbers.
Division (/): It can divide one number by another. It also checks for division by zero.
Square Root (√): It can calculate the square root of a single number.
Power (^): It can raise one number to the power of another.




Project Source Code:



<?php

$result = "";
$error_msg = "";

if(isset($_POST['num1']) && isset($_POST['num2']) && isset($_POST['operation']))
{
// Retrieve user's input from the form
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$operation = $_POST['operation'];

// Validate user's input
if(!is_numeric($num1) || !is_numeric($num2) && !($operation == "sqrt"))
{
$error_msg = "Please enter valid numbers";
}
elseif($operation == "div" && $num2 == 0)
{
$error_msg = "Cannot divide by zero";
}
else
{
// Perform the calculation based on the user's input
switch($operation)
{
case "add":
$result = $num1 + $num2;
break;
case "sub":
$result = $num1 - $num2;
break;
case "mul":
$result = $num1 * $num2;
break;
case "div":
$result = $num1 / $num2;
break;
case "sqrt":
$result = sqrt($num1);
break;
case "pwr":
$result = pow($num1, $num2);
break;
default:
$error_msg = "Invalid operation";
}
}
}

?>


<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<meta charset="UTF-8">

<style>

*{ box-sizing:border-box; }

body{ background-color:#f2f2f2; font-family:Arial, sans-serif; font-size:14px; }

#container{ width:400px; margin:50px auto; padding:20px; background-color:#fefefe;
border-radius:5px; box-shadow: 0px 0px 10px rgba(0,0,0,0.1); }

h1{ text-align:center; margin-bottom:25px; }

input[type=text]{ width:100%; padding:10px; border:none; border-radius:3px;
margin-bottom:20px; font-size:16px; color:#333; background-color:#f2f2f2;
box-shadow:inset 0px 1px 2px rgba(0,0,0,0.1); }

label{ display:inline-block; width:45%; font-size:16px; padding:10px; }

input[type=submit]{ display:inline-block; padding:10px 20px; border:none; border-radius:3px; width:100%;
cursor:pointer; background-color:#4caf50; color:#fff; font-size:16px;
transition: all 0.3s ease; }
input[type=submit]:hover{ background-color:#3e8e41; }

p{ margin-top:20px; font-size:24px; font-weight:bold; color:#fff; text-align:center; }

.result{ background-color:#999; border:1px solid #555; padding:10px;
margin:10px 0; text-align:center; }



</style>

</head>
<body>

<div id="container">

<h1>PHP Calculator</h1>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<input type="text" name="num1" id="num1" placeholder="Enter first number">
<input type="text" name="num2" id="num2" placeholder="Enter second number">

<br><br>

<label><input type="radio" name="operation" value="add"> Addition(+)</label>
<label><input type="radio" name="operation" value="sub"> Substraction(-)</label>
<label><input type="radio" name="operation" value="mul"> Multiplication(*)</label>
<label><input type="radio" name="operation" value="div"> Division(/)</label>
<label><input type="radio" name="operation" value="sqrt"> Square Root(√)</label>
<label><input type="radio" name="operation" value="pwr"> Power(^)</label>
<br>
<div><p style="color:red; font-size:18px; " ><?php echo $error_msg; ?></p></div>
<br>

<input type="submit" value="Calculate">
</form>

<div class="result">
<p>Result: <span id="result" style="cursor:pointer;"><?php echo $result; ?></span></p>
</div>

</div>

<script>

const result = document.getElementById("result");
const num1 = document.getElementById("num1");

result.addEventListener('click', function(){

num1.value = result.innerHTML;

});


</script>

</body>
</html>




Code Explanation:

PHP Code: - Defines two variables, $result and $error_msg, for displaying calculation results and error messages.
-Checks for the presence of 'num1', 'num2', and 'operation' values in the POST request.
- Retrieves and processes these values, including validation and calculation based on user input.
- Validates whether 'num1' and 'num2' are numeric and if the 'operation' is valid.
- Performs calculations based on the selected operation (addition, subtraction, multiplication, division, square root, or power), assigning the result to $result.
- In case of validation errors, assigns an error message to $error_msg.
- Finally, the calculated result or error message is displayed on the HTML page.

JavaScript Code: A simple JavaScript function is used to make the result clickable. 
When clicked, it copies the result to the 'num1' input field. This could be used for further calculations.



OUTPUT: