Java - Shapes Generator Project In Java Netbeans

How to Create a Shape Generator App In Java Netbeans

Java Project Tutorial - How To Create a Geometric Shapes Generator Project In Java Netbeans.


In this Java Tutorial we will see How To Make a Geometric Shapes Generator Project In Java Using Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.

What We Will Do In This Project:

- Create an inner class called DrawingPanel that extends JPanel.
- Create a method to generate random shapes type (e.g., circle, rectangle, triangle), with random values for position, and size.
- Create a method "createRegularPolygon", to create regular polygons like pentagons and hexagons.





Project Source Code:


package new_tutorials;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class ShapeGeneratorApp extends JFrame {
    
    private DrawingPanel drawingPanel;
    private JButton generateButton;

    public ShapeGeneratorApp()
    {
        setTitle("Shape Generator");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        setLocationRelativeTo(null);
        
        // Initialize the drawing panel and the "Generate Shape" button
        drawingPanel = new DrawingPanel();
        generateButton = new JButton("Generate Shape");
        generateButton.setFocusPainted(false);
        generateButton.setBorderPainted(false);
        generateButton.setBackground(new Color(63, 81, 181));
        generateButton.setForeground(Color.white);
        generateButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        generateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
              // Call the method to generate a random shape
                drawingPanel.generateRandomShape();
                
            }
        });
        
        // Create a panel to hold the button
        JPanel controlPanel = new JPanel();
        controlPanel.add(generateButton);
        
        // Set the layout and add the controls panel and drawing panel to the JFrame
        setLayout(new BorderLayout());
        add(controlPanel, BorderLayout.NORTH);
        add(drawingPanel, BorderLayout.CENTER);
        
    }
    
    // Inner class to handle the drawing panel
    private class DrawingPanel extends JPanel
    {
        private Shape currentShape;
        private Color currentColor;
        
        public DrawingPanel()
        {
            setBackground(Color.WHITE);
            currentColor = Color.BLACK;
        }
        
        // Method to generate a random shape
        public void generateRandomShape()
        {
            
            Random random = new Random();
            // Update the limit to include all shape types
            int ShapeType = random.nextInt(6);
            int x = random.nextInt(getWidth() - 50);
            int y = random.nextInt(getHeight() - 50);
            int size = random.nextInt(100) + 50;
            
            switch (ShapeType)
            {
                
                case 0: // circle
                    currentShape = new Ellipse2D.Double(x,y, size,size);
                    break;
                    
                case 1: // rectangle
                    int width = random.nextInt(100)+50;
                    int height = random.nextInt(100)+50;
                    currentShape = new Rectangle(x,y, width,height);
                    break;
                    
                case 2: // triangle
                    int[] xPoints = {x, x + size / 2, x + size};
                    int[] yPoints = {y + size, y, y + size};
                    currentShape = new Polygon(xPoints, yPoints,3);
                    break;
                    
                case 3: // square
                    currentShape = new Rectangle(x,y, size,size);
                    break;
                   
                case 4: // pentagon
                    currentShape = createRegularPolygon(x,y, size,5);
                    break;
                    
                case 5: // hexagon
                    currentShape = createRegularPolygon(x,y, size,6);
                    break;
            
            }
            
            // create a new color
            currentColor = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
            
            // Repaint the panel to show the newly generated shape
            repaint();        
        }
        
        
        // Method to create a regular polygon
        private Shape createRegularPolygon(int x, int y, int size, int sides)
        {
            GeneralPath path = new GeneralPath();
            double angle = 2 * Math.PI/sides;
            
            path.moveTo(x+size*Math.cos(0), y+size*Math.sin(0));
            
            for(int i = 1; i < sides; i++)
            {
                path.lineTo(x+size*Math.cos(angle*i), y+size*Math.sin(angle*i));
            }
            
            path.closePath();
            return path;
        }
        
        
        @Override
        protected void paintComponent(Graphics g){
            
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            
            // Check if there's a shape to draw
            if(currentShape != null)
            {
                g2d.setColor(currentColor);
                g2d.fill(currentShape);
            }
            
        }
        
    }
    
    
    public static void main(String[] args){
        SwingUtilities.invokeLater(()->{
        
            ShapeGeneratorApp shapeGenerator = new ShapeGeneratorApp();
            shapeGenerator.setVisible(true);
            
        });
    }
    
    
}


The Final Result:

circle

hexagon

pentagon

rectangle

square

triangle






JavaScript Random Number Generator

How To Create a Random Number Generator Using Javascript  


JavaScript Random Number Generator



In this Javascript tutorial, we will learn how to create a js code that generates random numbers within a given range.



Project Source Code:


<!DOCTYPE html>
<html>
<head>
<title>Random Number Generator</title>

<style>

*{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }

.container{ width: 50%; margin: 0 auto; text-align: center; }

input[type="number"]{ width: 50%; padding: 12px 20px; margin: 8px 0;
box-sizing: border-box;
border: 2px solid #ccc; border-radius: 4px;
}

button{ width: 100%; padding: 14px 20px; margin: 8px 0; border: none;
border-radius: 4px; background-color: #4caf50; color: #fff;
cursor: pointer; font-weight: bold;
}

#result{ font-size: 2em; width: 100%; margin-top: 20px; }

</style>

</head>
<body>

<div class="container">
<form>
<label for="min">Minimum Value:</label>
<input type="number" id="min">
<br>
<label for="max">Maximum Value:</label>
<input type="number" id="max">
<br>
<button type="button" id="generate-btn">Generate Random Number</button>
<br>
<input type="text" id="result" readonly>
</form>
</div>


<script>

// This script selects the HTML elements by their IDs and stores them in variables.
const generateBtn = document.getElementById("generate-btn");
const minValue = document.getElementById("min");
const maxValue = document.getElementById("max");
const result = document.getElementById("result");

// This function is executed when the generateBtn button is clicked.
generateBtn.addEventListener("click", function(){

// The min and max values are extracted from the input fields
// and converted to integers.
let min = parseInt(minValue.value);
let max = parseInt(maxValue.value);

// If the minimum value is greater than the maximum value,
// an alert is displayed and the function returns without generating a number.
if(min > max){
alert("Minimum value must be less than maximum value");
return;
}

// A random number between the minimum and maximum values (inclusive)
// is generated using the Math.floor and Math.random functions.
let randomNum = Math.floor(Math.random() * (max - min + 1)) + min;

// The generated random number is displayed in the result field.
result.value = randomNum;

});


</script>


</body>
</html>



Code Explanation:

This JavaScript code performs the following actions:

1 - Element Selection: The script selects specific HTML elements using their respective IDs and stores them in variables. These elements include:
* generateBtn: Represents the button triggering the number generation. 
* minValue: Represents the input field for the minimum value. 
* maxValue: Represents the input field for the maximum value. 
* result: Represents the output field where the generated number will be displayed.

2 - Event Listener: An event listener is attached to the generateBtn button, triggering the execution of the function whenever the button is clicked.

3 - Validation: The script checks if the minimum value is greater than the maximum value. If this condition is true, an alert is displayed informing the user that the minimum value must be less than the maximum value. The function then returns, preventing the generation of a number.

4 - Random Number Generation: If the minimum and maximum values are valid, the script proceeds to generate a random number between the provided range. 
It uses the Math.floor() and Math.random() functions to generate a random decimal number between 0 and 1 (exclusive). 
This decimal number is then multiplied by the difference between the maximum and minimum values and then rounded down using Math.floor(). The minimum value is added to the result to ensure the generated number falls within the desired range.

5 - Displaying the Result: Finally, the generated random number is assigned to the value property of the result field, which causes it to be displayed to the user.



OUTPUT:





Random Number Generator Using Javascript








Java - How To Create a Password Generator Project

How to Create a Password Generator App in Java NetBeans



In this Java Project Tutorial we will see How To Make a Password Generator Project In Java Using Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.

What We Will Do In This Project:

- Create checkboxes for users to select which character types should be included in the generated password (lowercase letters, uppercase letters, numbers, and special characters).
- Allow Users to set the desired length for the generated password using a spinner control.
Display the generated password in a text field, allowing users to easily copy it for their use.




Project Source Code:


package password_generator_app;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

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

    private JCheckBox lowerCaseCheckBox;
    private JCheckBox upperCaseCheckBox;
    private JCheckBox numbersCheckBox;
    private JCheckBox specialCharsCheckBox;
    private JSpinner lengthSpinner;
    private JTextField passwordTextField;
    private JButton generateButton;
    
    public Password_Generator_App(){
        // Set up the JFrame properties
        setTitle("Password Generator");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400,400);
        setLocationRelativeTo(null);
        initialize(); // initialize the user interface
    }
    
    
    private void initialize(){
        // Create checkboxes for character type selection
        lowerCaseCheckBox = new JCheckBox("Include LowerCase");
        upperCaseCheckBox = new JCheckBox("Include UpperCase");
        numbersCheckBox = new JCheckBox("Include Numbers");
        specialCharsCheckBox = new JCheckBox("Include Special Characters");
        
        lowerCaseCheckBox.setFocusPainted(false);
        lowerCaseCheckBox.setBorderPainted(false);
        lowerCaseCheckBox.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        upperCaseCheckBox.setFocusPainted(false);
        upperCaseCheckBox.setBorderPainted(false);
        upperCaseCheckBox.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        numbersCheckBox.setFocusPainted(false);
        numbersCheckBox.setBorderPainted(false);
        numbersCheckBox.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        specialCharsCheckBox.setFocusPainted(false);
        specialCharsCheckBox.setBorderPainted(false);
        specialCharsCheckBox.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        // Create a spinner for password length selection
        lengthSpinner = new JSpinner(new SpinnerNumberModel(8,4,20,1));
        
        // Create a text field to display the generated password
        passwordTextField = new JTextField(20);
        passwordTextField.setFont(new Font("Arial", Font.PLAIN, 16));
        passwordTextField.setEditable(false);
        
        // Create a button to generate passwords
        generateButton = new JButton("Generate Password");
        generateButton.setBackground(new Color(63,81,181));
        generateButton.setForeground(Color.white);
        generateButton.setFocusPainted(false);
        generateButton.setBorderPainted(false);
        generateButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        generateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            
                generatePassword();
                
            }
        });
        
        
        // Create panels to hold UI components
        JPanel mainPanel = new JPanel(new GridLayout(8,1,10,10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
        mainPanel.setBackground(Color.white);
        
        mainPanel.add(lowerCaseCheckBox);
        mainPanel.add(upperCaseCheckBox);
        mainPanel.add(numbersCheckBox);
        mainPanel.add(specialCharsCheckBox);
        
        JPanel lengthPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        lengthPanel.setBackground(Color.white);
        lengthPanel.add(new JLabel("Password Length"));
        lengthPanel.add(lengthSpinner);
        mainPanel.add(lengthPanel);
        
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.setBackground(Color.white);
        buttonPanel.add(generateButton);
        mainPanel.add(buttonPanel);
        mainPanel.add(passwordTextField);
        
        getContentPane().setBackground(Color.white);
        add(mainPanel);
        
    }
    
    
    private String generatePassword()
    {
        // Get the desired password length from the spinner
        int passwordLength = (int) lengthSpinner.getValue();
        
        // Define character sets for password generation
        String lowerCase = "abcdefghijklmnopqrstuvwxyz";
        String upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String numbers = "0123456789";
        String specialChars = "!@#$%^&*()_+-=[]{}|;:,.<>?";
        
        
        // Initialize the characters string based on user selections
        String characters = "";
        if(lowerCaseCheckBox.isSelected()) characters += lowerCase;
        if(upperCaseCheckBox.isSelected()) characters += upperCase;
        if(numbersCheckBox.isSelected()) characters += numbers;
        if(specialCharsCheckBox.isSelected()) characters += specialChars;
        
        // If no character type is selected, show an error message
        if (characters.isEmpty())
        {
            JOptionPane.showMessageDialog(this, "Please Select at Least one Character type");
            return "";
        }
        
        // Generate the password by selecting random characters from the characters string
        Random random = new Random();
        StringBuilder password = new StringBuilder();
        
        for(int i = 0; i < passwordLength; i++)
        {
           int randomIndex = random.nextInt(characters.length());
           char randomChar = characters.charAt(randomIndex);
           password.append(randomChar);
        }
        
        // Display the generated password in the text field
        passwordTextField.setText(password.toString());
        return password.toString();
        
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(() -> {
        
            try
            {
                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
            
            Password_Generator_App app = new Password_Generator_App();
            app.setVisible(true);
        
        });
        
        
    }

}


The Final Result:

How To Create a Password Generator Project In Java



Password Generator Project In Java

Java Password Generator Application


Java Password Generator Project


Password Generator Project In Java






download the source code