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






Using Python And Tkinter to Open, Read, and Save Text Files

How to Open, Read, and Save Text Files Using Python and Tkinter

How to Open, Read, and Save Text Files Using Tkinter in Python


In this Python tutorial we will create an application that allows users to open, read, and save text files using the Tkinter library for the graphical user interface. 
The application features a text editor and a menu bar for file operations, including open, save, and exit options.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter for GUI.
- VS Code Editor.




Project Source Code:



import tkinter as tk
from tkinter import ttk, filedialog

class TextFile_OpenReadSave:
def __init__(self, master):

# Initialize the main application
self.master = master
master.title("Open Read Save Text File")

# Styling
master.geometry("600x400")
master.configure(bg="#f0f0f0")

# Create a Text widget for text editing
self.text_editor = tk.Text(master)
self.text_editor.pack(expand=True, fill=tk.BOTH)

# Create a menu bar
self.menubar = tk.Menu(master)

# Create a File menu in the menu bar
self.file_menu = tk.Menu(self.menubar, tearoff=0)

# Add commands to the File menu
self.file_menu.add_command(label="Open", command = self.open_file)
self.file_menu.add_command(label="Save", command = self.save_file)
self.file_menu.add_separator()
self.file_menu.add_command(label="Exit", command = master.quit)

# Add the File menu to the menu bar
self.menubar.add_cascade(label="File", menu=self.file_menu)

# Configure the menu bar for the main window
master.config(menu=self.menubar)

def open_file(self):
# Ask user to select a file for opening
file_path = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt"),
        ("All Files", "*.*")])

if file_path:
# Read the contents of the selected file and insert it into the text editor
with open(file_path, "r") as file:
self.text_editor.delete("1.0", tk.END)
self.text_editor.insert(tk.END, file.read())


def save_file(self):
# Ask user to select a file for saving
file_path = filedialog.asksaveasfilename(defaultextension=".txt",
        filetypes=[("Text Files", "*.txt"),("All Files", "*.*")])

if file_path:
# Write the contents of the text editor to the selected file
with open(file_path, "w") as file:
file.write(self.text_editor.get("1.0", tk.END))




if __name__ == "__main__":
root = tk.Tk()
app = TextFile_OpenReadSave(root)
root.mainloop()


The Final Result:

Using Tkinter in Python to Open, Read, and Save Text Files









Java Colors Generator

How to Create a Color Codes Generator In Java Netbeans

How to Create a Color Codes Generator In Java Netbeans




In this Java Tutorial we will see How To Make a simple color generator application with a graphical interface using Java Swing In Netbeans.
The application allows users to generate random colors and displays the color labels along with their corresponding HEX values. 

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.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author 1BestCsharp
 */
public class Color_Generator_App extends JFrame{
    
    private JLabel[] colorLabels;
    private JTextField[] colorTextFields;
    private JButton generateColorsButton;
    
    public Color_Generator_App(){
        // Set the window title and properties
        setTitle("Color Generator");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400,300);
        setLocationRelativeTo(null);
        // Initialize the user interface
        intializeGUI();
    }
    
    private void intializeGUI(){
        // Create arrays to store color labels, text fields, and the generate button
        colorLabels = new JLabel[3];
        colorTextFields = new JTextField[3];
        generateColorsButton = new JButton("Generate Colors");
        
        // Create the main panel to hold components
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new GridLayout(3,2,10,10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
        
        // Create and add color labels and text fields to the main panel
        for(int i = 0; i < 3; i++)
        {
            colorLabels[i] = new JLabel("Color " + (i+1));
            colorLabels[i].setOpaque(true);
            colorLabels[i].setBackground(Color.white);
            colorLabels[i].setBorder(BorderFactory.createLineBorder(Color.black,1));
            colorLabels[i].setHorizontalAlignment(JLabel.CENTER);
            
            colorTextFields[i] = new JTextField();
            colorTextFields[i].setEditable(false);
            colorTextFields[i].setBackground(Color.white);
            colorTextFields[i].setBorder(BorderFactory.createLineBorder(Color.black,1));
            colorTextFields[i].setHorizontalAlignment(JTextField.CENTER);
            
            mainPanel.add(colorLabels[i]);
            mainPanel.add(colorTextFields[i]);
            
        }
        
        // Add the main panel to the center of the JFrame
        add(mainPanel, BorderLayout.CENTER);
        
        // Define the action when the "Generate Colors" button is clicked
        generateColorsButton.addActionListener(((e) -> {
            // Generate random colors and update labels and text fields
            for(int i = 0; i < 3; i++)
            {
              Color randomColor = generateRandomColor();  
              String colorCode = "#" + Integer.toHexString(randomColor.getRGB()).substring(2).toUpperCase();
              colorLabels[i].setBackground(randomColor);
              colorTextFields[i].setText(colorCode);
            }
            
        }));
        
        // Configure the "Generate Colors" button
        generateColorsButton.setPreferredSize(new Dimension(150,40));
        generateColorsButton.setFont(new Font("Arial", Font.PLAIN, 14));
        generateColorsButton.setBackground(new Color(30,144,255));
        generateColorsButton.setForeground(Color.WHITE);
        generateColorsButton.setFocusPainted(false);
        generateColorsButton.setBorderPainted(false);
        
        // Create a panel for the button and add it to the bottom of the JFrame
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(generateColorsButton);
        add(buttonPanel,BorderLayout.SOUTH);
        
    }
    
    
    // Method to generate a random color
    private Color generateRandomColor()
    {
        int red = (int) (Math.random()*256);
        int green = (int) (Math.random()*256);
        int blue = (int) (Math.random()*256);
        
        return new Color(red,green,blue);
    }
    

    public static void main(String[] args) {
        new Color_Generator_App().setVisible(true);
    }
    
}


The Final Result:

Java Color Generator

Generate Random Colors Using Java

Random colors generator in java

Color Codes Generator In Java

Java Color Generator





Java Create Line Chart

How to Create a Custom Line Chart In Java Netbeans

How to Create a Custom Line Chart In Java Netbeans


In this Java Tutorial we will see How To Create a Custom Line Chart from scratch with labeled axes, grid lines, and data points using graphics class and jpanel in java netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:


package linechart;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;


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

    // Constants for padding and labels
    private final int padding = 30;
    private final int labelPadding = 40;
    private final int axisLabelPadding = 20;
    private final int maxVerticalLabels = 5;
    private final int maxHorizontalLabels = 5;
    
    // Arrays for vertical and horizontal labels
    private String[] verticalLabels = {"0","25","50","75","100"};
    private String[] horizontalLabels = {"Label 1","Label 2","Label 3","Label 4","Label 5"};
    
    @Override
    protected void paintComponent(Graphics g){
        
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        
        // Calculate coordinates and dimensions
        int width = getWidth();
        int height = getHeight();
        int xStart = padding + labelPadding + axisLabelPadding;
        int yStart = height - padding - labelPadding;
        int xEnd = width - padding;
        int yEnd = padding + labelPadding;
        
        // Calculate step size for vertical and horizontal labels
        int yStep = (yStart - yEnd) / (maxVerticalLabels - 1);
        int xStep = (xEnd - xStart) / (maxHorizontalLabels - 1);
        
        // Draw vertical labels
        for(int i = 0; i < maxVerticalLabels; i++){
            int y = yStart - i * yStep;
            drawVerticalLabel(g2d, verticalLabels[i], padding / 2, y);
        }
        
        // Draw horizontal labels
        for(int i = 0; i < maxHorizontalLabels; i++){
            int x = xStart + i * xStep;
            //drawHorizontal(g2d, horizontalLabels[i], x, height - (padding / 2));
            drawHorizontalLabel(g2d, horizontalLabels[i], x, height - (padding / 2));
        }
        
        // Data for the chart
        int[] data = {40, 100, 75, 20, 55};
        int maxValue = 100;
        
        // Find the maximum value in the data
        for(int value : data){
            if(value > maxValue)
            {
                maxValue = value;
            }
        }
        
        // Draw chart background
        g2d.setColor(Color.white);
        g2d.fillRect(xStart, yEnd, xEnd - xStart, yStart - yEnd);
        
        // Draw chart border
        g2d.setColor(Color.black);
        g2d.drawRect(xStart, yEnd, xEnd - xStart, yStart - yEnd);
        
        // Draw horizontal grid lines
        int yGridCount = 5;
        for(int i = 0; i < yGridCount; i++){
            int y = yStart - i * yStep;
            g2d.setColor(Color.red);
            g2d.drawLine(xStart, y, xEnd, y);
        }
        
        // Draw vertical grid lines
        int xGridCount = data.length;
        for(int i = 0; i < xGridCount; i++){
            int x = xStart + i * xStep;
            g2d.setColor(Color.lightGray);
            g2d.drawLine(x, yEnd, x, yStart);
        }
        
        
        // Plot data points and connect with lines
        for(int i = 0; i < data.length; i++){
            g2d.setColor(Color.orange);
            int x = xStart + i * xStep;
            int y = yStart - data[i] * (yStart - yEnd) / maxValue;
            g2d.fillOval(x-5, y-5, 10, 10);
            
            // Connect data points with lines
            if( i > 0){
                int prevX = xStart + (i - 1) * xStep;
                int prevY = yStart - data[i - 1] * (yStart - yEnd) / maxValue;
                g2d.setStroke(new BasicStroke(2));
                g2d.setColor(Color.gray);
                g2d.drawLine(prevX, prevY, x, y);
            }
        }
        
        // Draw Chart Title
        g2d.setFont(new Font("Arial",Font.BOLD, 20));
        g2d.setColor(Color.red);
        String chartTitle = "Chart Title";
        g2d.drawString(chartTitle, (width - g2d.getFontMetrics().stringWidth(chartTitle)) / 2, padding);        
    }
    
    // Method to draw a vertical label with rotation
    private void drawVerticalLabel(Graphics2D g2d, String label, int x, int y){
        AffineTransform atf = new AffineTransform();
        atf.rotate(-Math.PI / 2);
        Font rotatedFont = g2d.getFont().deriveFont(atf);
        g2d.setFont(rotatedFont);
        g2d.setColor(Color.yellow);
        g2d.drawString(label, x + 30, y);
        g2d.setFont(g2d.getFont().deriveFont(atf));
    }
    
    // Method to draw a horizontal label
    private void drawHorizontalLabel(Graphics2D g2d, String label, int x, int y){
        g2d.setColor(new Color(248,239,186));
        g2d.drawString(label, x - g2d.getFontMetrics().stringWidth(label) / 2, y);
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        JFrame frame = new JFrame();
        frame.setTitle("Custom Line Chart");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setLocationRelativeTo(null);
        LineChart chartPanel = new LineChart();
        chartPanel.setBackground(Color.darkGray);
        frame.add(chartPanel);
        frame.setVisible(true);
        
    }

}




The Final Result:

Java Line Chart

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