Java - Create Dark Night Sky Animation

How to Create a Night Sky Animation with Stars and a Moon In Java Netbeans



In this Java Tutorial we will see How To Create a simple animated scene with stars moving across a dark night sky and a moon shining brightly. 
The animation gives the impression of a serene night with stars twinkling and a calm moon in the background.

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.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

/**
 *
 * @author 1BestCsharp
 */
public class DarkNightSky extends JPanel{

    private static final int FRAME_WIDTH = 800;
    private static final int FRAME_HEIGHT = 600;
    private static final int NUM_STARS = 100;
    private static final int STAR_SIZE = 5;
    private static final int ANIMATION_DELAY = 50;
    
    private final List<Point> stars;  // List to store the positions of stars
    private final Moon moon;
    
    public DarkNightSky()
    {
       stars = new ArrayList<>();  // Initialize the list of stars
       generateStars();
       moon = new Moon();
       
       Timer timer = new Timer(ANIMATION_DELAY, (e) -> {
           
           moveStars();
           repaint();
           
       });
       
       timer.start();
    }
    
    
    // Generate random star positions within the panel bounds
    private void generateStars(){
        Random rand = new Random();
        for(int i = 0; i < NUM_STARS; i++){
            int x = rand.nextInt(FRAME_WIDTH);
            int y = rand.nextInt(FRAME_HEIGHT);
            stars.add(new Point(x, y));
        }
    }
    
    
    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        // Fill the panel with a black background
        g.fillRect(0, 0, FRAME_WIDTH, FRAME_HEIGHT);
        g.setColor(Color.WHITE);
        
        // Draw stars as rectangles
        for(Point star : stars){
            g.fillRect(star.x, star.y, STAR_SIZE, STAR_SIZE);
        }
        
        // Draw the moon using the Moon class
        moon.draw(g);
        
    }
    
    
    public static void main(String[] args) {
        
        JFrame frame = new JFrame("Dark Night Sky");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
        frame.add(new DarkNightSky());
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    
    
    // Move stars in the animation, wrap around when reaching panel bounds
    private void moveStars(){
        
        for(Point star : stars){
            
            star.translate(1, 1);
            
            if(star.x > FRAME_WIDTH)
            {
                star.x = 0;
            }
            
            if(star.y > FRAME_HEIGHT)
            {
                star.y = 0;
            }
        }
        
    }
    
}

// Moon class to draw a white circle representing the moon
class Moon{
    
    private static final int MOON_RADIUS = 100;
    private static final int MOON_X = 600;
    private static final int MOON_Y = 100;
    
    // Draw the moon
    public void draw(Graphics g){
        g.setColor(Color.WHITE);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.fillOval(MOON_X, MOON_Y, MOON_RADIUS, MOON_RADIUS);
    }
    
    
}


The Final Result:









Database Data Navigation in PHP

How to Navigate and Display Database Records Using PHP

How to Navigate and Display Database Records Using PHP


In this PHP tutorial, we will see how to to retrieve product information from a database and display it within an HTML form. 
Users can navigate through the products by using navigation buttons, and the form fields will dynamically update to show the details of the selected product.



Project Source Code:



<?php

// Connect to the database
require_once "db_connect.php";

// Define the SQL query to select all products from the "product" table
$query = "SELECT * FROM `product`";

// Prepare the SQL statement
$stmt = $conn -> prepare($query);

// Execute the SQL statement
$stmt->execute();

// Fetch all the results from the statement and store them in an array
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Initialize an empty array to store the products
$products = array();

foreach( $results as $row ){
$product = array("id"=>$row["id"],
"name"=>$row["name"],
"price"=>$row["price"],
"image"=>$row["image"]
);

// Add the product array to the products array
array_push($products, $product);
}


?>

<!DOCTYPE html>
<html>
<head>
<title>Data Navigation</title>
<style>

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

form{ background-color:#fff; padding:20px; width:500px; margin: 25px auto;
border-radius:5px; box-shadow: 0 0 10px rgba(0,0,0,0.2); }
h1{ text-align:center; color:#333; margin-bottom:20px; }

.form-row{ margin:10px 0; }

input{ padding:10px; margin:10px 0; border:1px solid #ccc;
border-radius:4px; box-sizing:border-box; width:100%; }

button{ background-color:#4caf50; color:#fff; padding:10px 20px; border:none;
border-radius:4px; cursor:pointer; margin-top:10px; width:24%;
font-size:16px; }

button:hover{ background-color:#45a049; }

#image{ display:flex; align-items:flex-start; }

#image label{ margin-right:10px; }

#image img{ margin:10px; width:50%; height:150px; border-radius:5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.3); }

</style>
</head>
<body>

<form id="product-form">
<h1>Product Information</h1>
<div class="form-row">
<label for="product-id">ID:</label>
<input type="text" id="product-id" name="product-id">
</div>
<div class="form-row">
<label for="product-name">Name:</label>
<input type="text" id="product-name" name="product-name">
</div>
<div class="form-row">
<label for="product-price">Price:</label>
<input type="text" id="product-price" name="product-price">
</div>
<div class="form-row">
<div id="image">
<label for="product-image">Image:</label>
<img id="product-image" src="">
</div>
</div>
<div class="form-row">
<button type="button" id="btn-first">First</button>
<button type="button" id="btn-prev">Previous</button>
<button type="button" id="btn-next">Next</button>
<button type="button" id="btn-last">Last</button>
</div>

<script>

// convert the PHP array to a JavaScript object in JSON format.
const products = <?php echo json_encode($products); ?>

// Get the buttons
const btnFirst = document.getElementById('btn-first');
const btnNext = document.getElementById('btn-next');
const btnPrevious = document.getElementById('btn-prev');
const btnLast = document.getElementById('btn-last');

// Define a variable to keep track of the current index
let currentIndex = 0;

// Function to update the form fields based on the current index
function updateForm(){

const product = products[currentIndex];

document.getElementById('product-id').value = product.id;
document.getElementById('product-name').value = product.name;
document.getElementById('product-price').value = product.price;
document.getElementById('product-image').src = product.image;

}

// Function to handle button clicks
function handleButtonClick(e)
{
switch(e.target.id){
case 'btn-first':
currentIndex = 0;
break;
case 'btn-prev':
currentIndex = Math.max( currentIndex - 1, 0 );
break;
case 'btn-next':
currentIndex = Math.min( currentIndex + 1, products.length - 1 );
break;
case 'btn-last':
currentIndex = products.length - 1;
break;
default:
break;
}

updateForm();

}

// Add event listeners to the buttons
btnFirst.addEventListener('click', handleButtonClick);
btnNext.addEventListener('click', handleButtonClick);
btnPrevious.addEventListener('click', handleButtonClick);
btnLast.addEventListener('click', handleButtonClick);

// Initialize the form
updateForm();


</script>


</body>
</html>



Code Explanation:

PHP Section: This PHP code connects to a database using "db_connect.php," defines and executes an SQL query to select all products from a "product" table, fetches and stores the results in an array, and constructs an array of product information.

HTML/JavaScript Section: This code generates an HTML form with fields for product information.
It includes navigation buttons (First, Previous, Next, Last) to move between products and applies CSS styles.
JavaScript manages button clicks, updates form fields with product data, and keeps track of the current product.
listeners are added for button interaction, and the form is initialized through the updateForm function.



OUTPUT:


Database Data Navigation in PHP

Data Navigation in PHP




if you want the source code click on the download button below










Java Combobox With JTextArea

How to Add TextArea to a Combobox In Java Netbeans

Java Combobox With JTextArea


In this Java Tutorial we will see How To Create a JCombobox With JTextArea Inside It 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.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListCellRenderer;

/**
 *
 * @author 1BestCsharp
 */
public class TextAreaComboboxFrame extends JFrame{
    
    private JComboBox<TextAreaComboboxElement> comboBox;
    private JTextArea displayTextArea;
    
    public TextAreaComboboxFrame(){
        // Set up the JFrame
        setTitle("TextArea Combobox");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // Set the layout manager for the JFrame
        setLayout(new FlowLayout());
        // Create a JComboBox and set its renderer
        comboBox = new JComboBox<>();
        comboBox.setRenderer(new TextAreaComboboxRenderer());
        
        // Add three items with multiline text to the combobox
        comboBox.addItem(new TextAreaComboboxElement("Item 1", "This is the first item.\nIt has multiple lines."));
        comboBox.addItem(new TextAreaComboboxElement("Item 2", "This is the second item.\nIt also has multiple lines."));
        comboBox.addItem(new TextAreaComboboxElement("Item 3", "This is the third item.\nIt's multiline as well."));
        
        // Add an item listener to handle item selection
        comboBox.addItemListener((e) -> {
           
            TextAreaComboboxElement selectedItem = (TextAreaComboboxElement)comboBox.getSelectedItem();
            
            if(selectedItem != null){
                displayTextArea.setText(selectedItem.getText());
            }
            
        });
        
        add(comboBox);
        displayTextArea = new JTextArea(5,20);
        displayTextArea.setEditable(false);
        add(new JScrollPane(displayTextArea));
        setSize(400,400);
        setLocationRelativeTo(null);
        
        // Set the initial text in the display area
        TextAreaComboboxElement initialItem = comboBox.getItemAt(0);
        displayTextArea.setText(initialItem.getText());
        
    }
    
    
    
    
    
    // Create an Inner class representing elements in the combobox
    public static class TextAreaComboboxElement{
        private final String label;
        private final String text;
        
        // constructor
        public TextAreaComboboxElement(String label, String text){
            this.label = label;
            this.text = text;
        }
        
        // Getters
        public String getLabel(){ return label; }
        
        public String getText(){ return text; }
        
    }
    
    
    // Create an Inner class representing the renderer for the combobox
    private class TextAreaComboboxRenderer extends JPanel implements ListCellRenderer<TextAreaComboboxElement>{

        private final JLabel label;
        private final JTextArea textArea;
        
        public TextAreaComboboxRenderer(){
            setLayout(new BorderLayout());
            label = new JLabel();
            add(label, BorderLayout.NORTH);
            textArea = new JTextArea();
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            textArea.setEditable(false);
            add(textArea, BorderLayout.CENTER);
        }
        
        // Implement the rendering of combobox elements
        @Override
        public Component getListCellRendererComponent(JList<? extends TextAreaComboboxElement> list, TextAreaComboboxElement value, int index, boolean isSelected, boolean cellHasFocus) {
            // Set the label and text of the renderer components
            label.setText(value.getLabel());
            textArea.setText(value.getText());
            // Set the background and foreground based on selection
            if(isSelected){
                setBackground(Color.BLACK);
                getComponent(0).setForeground(Color.YELLOW);
            }
            else
            {
                setBackground(list.getBackground());
                getComponent(0).setForeground(list.getForeground());
                //setForeground(list.getForeground());
            }
            
            return this;
            
        }
        
    }
    
    
    
    public static void main(String[] args) {
        TextAreaComboboxFrame frame = new TextAreaComboboxFrame();
        frame.setVisible(true);
    }

}


The Final Result:


How to Add TextArea to a Combobox In Java Netbeans


How to Add JTextArea to a JCombobox In Java Netbeans