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






Java Create 3D Bar Chart

How to Create a Custom 3D Bar Chart In Java Netbeans



In this Java Tutorial we will see How To Create a Custom 3D Bar Chart from scratch using graphics class in java netbeans.
Note: The code generates random bar heights for demonstration purposes. 
In a real-world scenario, you would replace the random heights with actual data values for a meaningful representation of the chart.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:


package threedbarchart;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Polygon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

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

    private ThreeDBarChartPanel chartPanel;
    
    public ThreeDBarChart()
    {
        setTitle("3D Bar Chart");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500,500);
        setLocationRelativeTo(null);
        setResizable(false);
        
        chartPanel = new ThreeDBarChartPanel();
        getContentPane().add(chartPanel, BorderLayout.CENTER);
        
        JButton rotateButton = new JButton("Rotate");
        rotateButton.setBorderPainted(false);
        rotateButton.setFocusPainted(false);
        rotateButton.setBackground(new Color(50,10,20));
        rotateButton.setForeground(Color.white);
        rotateButton.setFont(new Font("Arial", Font.BOLD, 18));
        
        rotateButton.addActionListener((e) -> {
           
            chartPanel.rotateChart();
            
        });
        
        
        JPanel controlPanel = new JPanel();
        controlPanel.add(rotateButton);
        getContentPane().add(controlPanel, BorderLayout.SOUTH);
        
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        new ThreeDBarChart().setVisible(true);
        
    }

}




class ThreeDBarChartPanel extends JPanel
{
    // Define RGB color codes
    Color colorSideFace = new Color(248,111,21);
    Color colorTopFace = new Color(250,194,24);
    Color colorFrontFace = new Color(222,179,173);
  

    public void rotateChart()
    {
        repaint();
    }
    
    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        
        int width = getWidth();
        int height = getHeight();
        
        // Clear the panel
        g.setColor(Color.white);
        g.fillRect(0, 0, width, height);
        
        g.setColor(Color.darkGray);
        
        // Calculate the number of bars and their dimensions
        int numBars = 5;
        int barWidth = 40;
        int barSpacing = 20;
        int baseX = (width - (numBars * (barWidth + barSpacing) - barSpacing))/2;
        int baseY = height - 100;
        
        // Draw 3D bars
        for(int i = 0; i < numBars; i++)
        {
            int x = baseX + i * (barWidth + barSpacing);
            // Random heights for demonstration
            int barheight = (int) (Math.random() * 200)+50;
            // Depth of the bars
            int z = 10;
            // Draw the front face
            g.fillRect(x, baseY - barheight, barWidth, barheight);
            g.setColor(colorFrontFace);
            
            // Draw the top face
            Polygon topFace = new Polygon();
            topFace.addPoint(x, baseY - barheight);
            topFace.addPoint(x + barWidth, baseY - barheight);
            topFace.addPoint(x + barWidth + z, baseY - barheight - z);
            topFace.addPoint(x + z, baseY - barheight - z);
            
            g.fillPolygon(topFace);
            g.setColor(colorTopFace);
            
            // Draw the side face
            Polygon sideFace = new Polygon();
            sideFace.addPoint(x + barWidth, baseY - barheight);
            sideFace.addPoint(x + barWidth, baseY);
            sideFace.addPoint(x + barWidth + z, baseY - z);
            sideFace.addPoint(x + barWidth + z, baseY - barheight - z);
            
            g.fillPolygon(sideFace);
            g.setColor(colorSideFace);
            
        }
        
        // Draw horizontal axis labels
        int axisLabelX = baseX - 5;
        int axisLabelY = baseY + 20;
        g.setColor(Color.black);
        
        g.drawString("Label 1", axisLabelX, axisLabelY);
        g.drawString("Label 2", axisLabelX + barWidth + barSpacing, axisLabelY);
        g.drawString("Label 3", axisLabelX + 2 * (barWidth + barSpacing), axisLabelY);
        g.drawString("Label 4", axisLabelX + 3 * (barWidth + barSpacing), axisLabelY);
        g.drawString("Label 5", axisLabelX + 4 * (barWidth + barSpacing), axisLabelY);
        
        // Draw vertical axis labels
        int numTicks = 5;
        int tickSpacing = (baseY - 50) / numTicks;
        g.drawString("0", axisLabelX - 20, baseY - 5);
        
        for(int i = 1; i <= numTicks; i++)
        {
            int tickValue = 40 + i * 40;
            g.drawString(Integer.toString(tickValue), axisLabelX-30, baseY-i*tickSpacing);
        }
        
        g.drawString("", axisLabelX-60, height/2);
        
    }
    
}


The Final Result:






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