Java - Create Custom Checkbox

How to Create a Custom JCheckBox In Java Netbeans

How to Create a Custom JCheckBox In Java Netbeans




In this Java Tutorial we will see How To instead of using the default JCheckBox you can create and design your own custom checkbox using Graphics in Java Swing.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.

What This Project Do:

create a simple custom checkbox with Java Swing, allowing users to toggle its state by clicking on it. 
The checkbox is visually represented with a filled rectangle, a border, and a checkmark when checked.





Project Source Code:


package new_tutorials;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author 1BestCsharp
 */
public class CustomCheckBox extends JPanel {
    
    private boolean checked = false;
    
    public CustomCheckBox(){
        setPreferredSize(new Dimension(100, 100));
        setBackground(Color.white);
        
        addMouseListener(new MouseAdapter() {
            
            @Override
            public void mouseClicked(MouseEvent e){
                checked = !checked;
                repaint();
            }
            
        });
    }
    
    @Override
    protected void paintComponent(Graphics g){
        
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        
        // Change the checkbox background color when selected to black
        if(checked)
        {
            g2d.setColor(Color.red);
        }
        else
        {
            g2d.setColor(Color.white);
        }
        
        g2d.fillRect(10, 10, 30, 30);
        
        // Draw the checkbox border
        g2d.setColor(Color.gray);
        g2d.setStroke(new BasicStroke(2));
        g2d.drawRect(10, 10, 30, 30);
        
        // If checked, draw a checkmark
        if(checked)
        {
            g2d.setColor(Color.white);
            g2d.setStroke(new BasicStroke(4));
            g2d.drawLine(15, 25, 20, 30);
            g2d.drawLine(20, 30, 35, 15);
        }
        
        // Draw the label
        g2d.setColor(Color.black);
        g2d.setFont(new Font("Arial", Font.BOLD, 14));
        g2d.drawString("Custom Check Box", 50, 30);
    }
    
    
    public static void main(String[] args) {
        JFrame frame = new JFrame("Custom CheckBox");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setSize(400, 100);
        frame.add(new CustomCheckBox());
        frame.setVisible(true);
    }
    

}


The Final Result:

Create a Custom CheckBox In Java Netbeans Using Graphics

Create a Custom CheckBox In Java





Share this

Related Posts

Previous
Next Post »