Affichage des articles dont le libellé est Graphics. Afficher tous les articles
Affichage des articles dont le libellé est Graphics. Afficher tous les articles

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:









Java Create Pie / Donut Chart

How to Create a Custom Pie and Donut Chart In Java Netbeans



In this Java Tutorial we will see How To Create a Custom Pie Chart from scratch using graphics class in java netbeans.
We Will also see how to create a donut chart.
Each chart has three slices is drawn based on the percentage data provided with custom colors (yellow, blue, green) .

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code For The Pie Chart:


package piechart;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author 1BestCsharp
 */
public class PieChart extends JFrame {
    
    private PieChartPanel pieChartPanel;
    
    public PieChart(){
        setTitle("Pie Chart");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(550,400);
        setLocationRelativeTo(null);
        
        pieChartPanel = new PieChartPanel();
        pieChartPanel.setBackground(Color.white);
        add(pieChartPanel);
        setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        new PieChart();
        
    }
   
}


// Panel class for displaying the pie chart
class PieChartPanel extends JPanel
{
    // Custom slice colors for the pie chart    
    private Color[] sliceColors = {Color.decode("#FEC107"),
                                   Color.decode("#2196F3"),
                                   Color.decode("#4CAF50")
                                  };
    // Initial data values representing percentages
    private int[] data = {40, 30, 30};
    
    // Override the paintComponent method to customize the drawing of the panel
    @Override
    protected void paintComponent(Graphics g){
        
        super.paintComponent(g);
        // Call the method to draw the pie chart
        drawPieChart(g);
        
    }
    
    // Method to draw the pie chart
    private void drawPieChart(Graphics g){
        // Create a Graphics2D object
        Graphics2D g2d = (Graphics2D) g;
        // Get the width of the panel
        int width = getWidth();
        // Get the height of the panel
        int height = getHeight();
        // Determine the diameter of the pie chart
        int diameter = Math.min(width, height) - 20;
        // Calculate the x-coordinate for the pie chart
        int x = (width - diameter) / 2;
        // Calculate the y-coordinate for the pie chart
        int y = (height - diameter) / 2;
        // Initialize the starting angle for the first slice of the pie chart
        int startAngle = 0;
        
        for(int i = 0; i < data.length; i++){
            // Calculate the arc angle for the current slice
            int arcAngle = (int) ((double) data[i] / 100 * 360);
            // Set the color for the current slice
            g2d.setColor(sliceColors[i]);
            // Fill the arc representing the slice
            g2d.fillArc(x, y, diameter, diameter, startAngle, arcAngle);
            // Update the starting angle for the next slice
            startAngle += arcAngle;
        }
        
        // Draw labels or legends for each slice
        // Set the x-coordinate for the legend
        int legendX = width - 110;
        // Set the initial y-coordinate for the legend
        int legendY = 20;
        
        for(int i = 0; i < data.length; i++)
        {
            // Set the color for the legend box
            g2d.setColor(sliceColors[i]);
            // Fill the legend box with color
            g2d.fillRect(legendX, legendY, 20, 20);
            // Set the text color for the legend
            g2d.setColor(Color.black);
            // Draw the legend text with slice number and percentage
            g2d.drawString("Slice " + (i + 1) + ": " + data[i] + "%", legendX + 30, legendY + 15);
            // Update the y-coordinate for the next legend entry
            legendY += 30;
        }
        
    }
    
}




   

Project Source Code For The Donut Chart:


package piechart;


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author 1BestCsharp
 */
public class DonutChart extends JFrame {
    
    private DonutChartPanel donutChartPanel;
    
    public DonutChart(){
        setTitle("Donut Chart");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(550,400);
        setLocationRelativeTo(null);
        
        donutChartPanel = new DonutChartPanel();
        donutChartPanel.setBackground(Color.white);
        add(donutChartPanel);
        setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        new DonutChart();
        
    }
   
}


// Panel class for displaying the pie chart
class DonutChartPanel extends JPanel
{
    //private Color[] sliceColors = {Color.decode("#3498db"), Color.decode("#e74c3c"), Color.decode("#2ecc71")}; // Modern slice colors
    //private Color[] sliceColors = {Color.decode("#FF6B6B"), Color.decode("#74B9FF"), Color.decode("#55E6C1")}; // Custom slice colors
    private Color[] sliceColors = {Color.decode("#FF5733"), Color.decode("#33FFB2"), Color.decode("#3360FF")}; // Updated colors
    
    
    // Custom slice colors for the pie chart    
    /*private Color[] silceColors = {Color.decode("#FEC107"),
                                   Color.decode("#2196F3"),
                                   Color.decode("#4CAF50")
                                  };
*/
    // Initial data values representing percentages
    private int[] data = {75, 20, 5};
    
    // Override the paintComponent method to customize the drawing of the panel
    @Override
    protected void paintComponent(Graphics g){
        
        super.paintComponent(g);
        // Call the method to draw the pie chart
        drawDonutChart(g);
        
    }
    
    // Method to draw the pie chart
    private void drawDonutChart(Graphics g){
        // Create a Graphics2D object
        Graphics2D g2d = (Graphics2D) g;
        // Get the width of the panel
        int width = getWidth();
        // Get the height of the panel
        int height = getHeight();
        // Determine the diameter of the pie chart
        int outerDiameter = Math.min(width, height) - 20;
        int innerDiameter = outerDiameter / 2;
        // Calculate the x-coordinate for the pie chart
        int x = (width - outerDiameter) / 2;
        // Calculate the y-coordinate for the pie chart
        int y = (height - outerDiameter) / 2;
        // Initialize the starting angle for the first slice of the pie chart
        int startAngle = 0;
        
        for(int i = 0; i < data.length; i++){
            // Calculate the arc angle for the current slice
            int arcAngle = (int) ((double) data[i] / 100 * 360);
            // Set the color for the current slice
            g2d.setColor(sliceColors[i]);
            // Fill the arc representing the slice
            g2d.fillArc(x, y, outerDiameter, outerDiameter, startAngle, arcAngle);
            g2d.setColor(getBackground());
            g2d.fillArc(x+(outerDiameter - innerDiameter) / 2, y + (outerDiameter - innerDiameter) / 2, innerDiameter, innerDiameter, 0, 360);
            // Update the starting angle for the next slice
            startAngle += arcAngle;
        }
        
        // Draw labels or legends for each slice
        // Set the x-coordinate for the legend
        int legendX = width - 110;
        // Set the initial y-coordinate for the legend
        int legendY = 20;
        
        for(int i = 0; i < data.length; i++)
        {
            // Set the color for the legend box
            g2d.setColor(sliceColors[i]);
            // Fill the legend box with color
            g2d.fillRect(legendX, legendY, 20, 20);
            // Set the text color for the legend
            g2d.setColor(Color.black);
            // Draw the legend text with slice number and percentage
            g2d.drawString("Slice " + (i + 1) + ": " + data[i] + "%", legendX + 30, legendY + 15);
            // Update the y-coordinate for the next legend entry
            legendY += 30;
        }
        
    }
    
}



    



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













Java - How to create a cube in java swing

How to Create a Cube in Java NetBeans

How to Create a Cube in Java NetBeans


In this Java Tutorial we will see How To draw a cube with orange outline on a black background using a JPanel, Graphics and Graphics2D objects in Java Swing using NetBeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.


What We Will Do In This Project:
- Create a drawLine method to draw lines on the panel representing the edges of the cube.
- Create a drawRectangularFace method to draw a rectangular face of the cube by connecting lines.
- Create a connectFaces method to connects the front and back faces of the cube by drawing additional lines.






Project Source Code:


package new_tutorials;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

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

    private static final int FRAME_WIDTH = 800;
    private static final int FRAME_HEIGHT = 600;
    private static final int CUBE_SIZE = 200;
    
    public ThreeDCube(){
        setPreferredSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT));
    }
    
    @Override
    protected void paintComponent(Graphics g){
        
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        // Set the stroke to a thicker line
        g2d.setStroke(new BasicStroke(5));
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, FRAME_WIDTH, FRAME_HEIGHT);
        // Calculate the position to center the cube
        int x = (FRAME_WIDTH - CUBE_SIZE) / 2;
        int y = (FRAME_HEIGHT - CUBE_SIZE) / 2;
        // Draw front face
        drawRectangularFace(g2d, x, y, CUBE_SIZE, CUBE_SIZE);
        // Draw back face
        drawRectangularFace(g2d, x+CUBE_SIZE/2, y-CUBE_SIZE/2, CUBE_SIZE, CUBE_SIZE);
        // Connect front and back faces
        connectFaces(g2d, x, y, x+CUBE_SIZE/2, y-CUBE_SIZE/2, CUBE_SIZE, CUBE_SIZE);
        
    }
    
    
    // Method to draw a lines
    private void drawLine(Graphics2D g2d, int x1, int y1, int x2, int y2){
        
        g2d.setColor(Color.ORANGE);
        g2d.drawLine(x1, y1, x2, y2);
        
    }
    
    
    // Method to draw a rectangular face
    private void drawRectangularFace(Graphics2D g2d, int x, int y, int width, int height)
    {
        drawLine(g2d, x, y, x+width, y);
        drawLine(g2d, x+width, y, x+width, y+height);
        drawLine(g2d, x+width, y+height, x, y+height);
        drawLine(g2d, x, y+height, x, y);
    }
    
    
    // Method to connect the front and back faces
        private void connectFaces(Graphics2D g2d, int x1, int y1, int x2, int y2, int width, int height)
    {
        drawLine(g2d, x1, y1, x2, y2);
        drawLine(g2d, x1+width, y1, x2+width, y2);
        drawLine(g2d, x1+width, y1+height, x2+width, y2+height);
        drawLine(g2d, x1, y1+height, x2, y2+height);
    }
    
    
    public static void main(String[] args) {
        JFrame frame = new JFrame("3 D Cube");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new ThreeDCube());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    
}





How to Draw a Cube in Java NetBeans