Affichage des articles dont le libellé est Graphics2D. Afficher tous les articles
Affichage des articles dont le libellé est Graphics2D. 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 Gradient Buttons

How to Create Buttons with Gradient Backgrounds In Java Netbeans

Gradient Buttons In Java


In this Java Tutorial we will see How To Create custom jbutton with a gradient background that transitions from one color to another 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.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
 *
 * @author 1BestCsharp
 */
public class GradientButton extends JButton{

    private Color startColor;
    private Color endColor;
    
    public GradientButton(String text, Color startColor, Color endColor){
        
        super(text);
        this.startColor = startColor;
        this.endColor = endColor;
        setContentAreaFilled(false);
        setFocusPainted(false);
        setForeground(Color.WHITE);
        setPreferredSize(new Dimension(150, 70));  
        setCursor(new Cursor(Cursor.HAND_CURSOR));
    }
    
    
    @Override
    protected void paintComponent(Graphics g){
        
        Graphics2D g2d = (Graphics2D)g.create();
        // Create a gradient paint
        GradientPaint gradientPaint = new GradientPaint(
                new Point2D.Float(0,0), startColor,
                new Point2D.Float(0,getHeight()), endColor
        );
        
        g2d.setPaint(gradientPaint);
        // Fill the button background with the gradient
        g2d.fillRect(0, 0, getWidth(), getHeight());
        
        super.paintComponent(g);
        
        g2d.dispose();
        
    }
    
    
    public static void main(String[] args) {
        
        JFrame frame = new JFrame("Gradient Button");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        
        GradientButton button = new GradientButton("Button", Color.GREEN, Color.BLUE);
        
        frame.add(button);
        frame.setSize(300, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        
    }
    
}


The Final Result:

Buttons with Gradient Backgrounds In Java 1

Buttons with Gradient Backgrounds In Java 2

Buttons with Gradient Backgrounds In Java 3

Buttons with Gradient Backgrounds In Java 4

Buttons with Gradient Backgrounds In Java 5

Buttons with Gradient Backgrounds In Java 6






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