Java - Create Custom Toggle Buttons

How to Create a Custom JToggleButton in Java Netbeans

How to Create a Custom JToggleButton in Java Netbeans


In this Java Tutorial we will see How To Create a custom toggle button component with sliding animation, Gradient backgrounds, Multiple color themes and Status indicator dot when activated In Java Using Netbeans.


What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:



/**
 *
 * @author 1BestCsharp
 * 
 */
public class CustomToggleButton extends JToggleButton {
    // Current position of the toggle button (0 = off, 1 = on)
    private float position = 0;
    // Position used for the glow animation effect
    private float glowPosition = 0;
    // Default background color when the toggle is off
    private Color toggleColor = new Color(200, 200, 220);
    // Default color when the toggle is active/on
    private Color activeColor = new Color(130, 90, 255);
    // Timer for handling smooth animations
    private Timer animationTimer;
    // Duration of the toggle animation in milliseconds
    private static final int ANIMATION_DURATION = 200;
    
    
    public CustomToggleButton(){
        
        setPreferredSize(new Dimension(70*2, 35*2));
        setContentAreaFilled(false);
        setBorderPainted(false);
        setFocusPainted(false);
        setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        // Initialize animation timer that updates every 16ms
        animationTimer = new Timer(16, e ->{
            // Determine target position based on selected state
            float targetPosition = isSelected() ? 1 : 0;
            // Calculate step size for smooth animation
            float step = 1.0f / (ANIMATION_DURATION / 16.0f);
            
            // Animate toggle position
            if(position < targetPosition){
                // Move position towards 1 (on state)
                position = Math.min(position + step, 1);
                // Apply easing function to smooth the movement
                glowPosition = easeInOut(position);
                repaint();
            }
            else if(position > targetPosition){
                // Move position towards 0 (off state)
                position = Math.max(position - step, 0);
                // Apply easing function to smooth the movement
                glowPosition = easeInOut(position);
                repaint();
            }
        });
        
        // Start animation when the toggle state changes
        addItemListener(e -> {
            
            if(!animationTimer.isRunning()){
                animationTimer.start();
            }
        
        });
        
        
    }
    
    @Override
    protected void paintComponent(Graphics g){
        // Create a new Graphics2D object with anti-aliasing enabled
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        
        // Calculate dimensions for the toggle button
        int width = getWidth();
        int height = getHeight();
        int toggleWidth = width - 4;
        int toggleHeight = height - 4;
        int diameter = toggleHeight - 4;
        
        // Create rounded rectangle for button background
        RoundRectangle2D background = new RoundRectangle2D.Float(
                2, 2, toggleWidth, toggleHeight, toggleHeight, toggleHeight
        );
        
        // Create gradient for glass effect
        GradientPaint gradientBackground = new GradientPaint(
                0, 0, new Color(255, 255, 255, 50),
                0, height, new Color(255, 255, 255, 10)
        );
        
        // Draw main background
        g2d.setColor(isSelected() ? activeColor : toggleColor);
        g2d.fill(background);
         // Apply glass effect gradient
        g2d.setPaint(gradientBackground);
        g2d.fill(background);
        
        // Add subtle inner shadow to background
        g2d.setColor(new Color(0,0,0,10));
        g2d.setStroke(new BasicStroke(1.5f));
        g2d.draw(background);
        
        // Calculate position of the toggle circle
        float circleX = 4 + (toggleWidth - diameter - 4) * glowPosition;
        float circleY = 4;
        
        // Draw the main toggle circle 
        g2d.setColor(Color.WHITE);
        Ellipse2D circle = new Ellipse2D.Float(circleX, circleY, diameter, diameter);
        g2d.fill(circle);
        
        // Add gradient to the toggle circle
        GradientPaint gradientKnob = new GradientPaint(
                circleX, circleY, new Color(255, 255, 255),
                circleX, circleY + diameter, new Color(240, 240, 240)
        );
        
        g2d.setPaint(gradientKnob);
        g2d.fill(circle);
        
        // Add border to toggle circle
        g2d.setColor(new Color(0, 0 , 0, 30));
        g2d.setStroke(new BasicStroke(1f));
        g2d.draw(circle);
        
        // Draw status indicator dot when selected
        if(isSelected()){
            float dotSize = diameter * 0.5f;
            float dotX = circleX + (diameter - dotSize) / 2;
            float dotY = circleY + (diameter - dotSize) / 2;
            g2d.setColor(activeColor);
            g2d.fill(new Ellipse2D.Float(dotX, dotY, dotSize, dotSize));
        }
        
        // Clean up graphics resources
        g2d.dispose();
                
        
    }
    
    
    
    // Easing function to create smooth acceleration and deceleration
    private float easeInOut(float t){
        
        return t < 0.5f ? 2 * t * t : -1 + (4 - 2 * t) * t;
        
    }
    
    // Method to change the active color of the toggle
    public void setActiveColor(Color color){
        this.activeColor = color;
        repaint();
    }
    
    
    public static void main(String[] args) {
        
        JFrame frame = new JFrame("Toggle Buttons");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setBackground(Color.WHITE);
        frame.setSize(600, 250);
        frame.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 20));
        
        CustomToggleButton cbtn = new CustomToggleButton();
        CustomToggleButton toggleBlue = new CustomToggleButton();
        CustomToggleButton toggleGreen = new CustomToggleButton();
        CustomToggleButton toggleRed = new CustomToggleButton();
        CustomToggleButton toggleBlack = new CustomToggleButton();
        CustomToggleButton toggleYellow = new CustomToggleButton();
        
        toggleBlue.setActiveColor(new Color(64, 150, 255));
        toggleGreen.setActiveColor(new Color(75, 210, 140));
        toggleRed.setActiveColor(new Color(239, 68, 68));
        toggleBlack.setActiveColor(new Color(20, 5, 5));
        toggleYellow.setActiveColor(new Color(241, 196, 15));
        
        
        frame.add(cbtn);
        frame.add(toggleBlue);
        frame.add(toggleGreen);
        frame.add(toggleRed);
        frame.add(toggleBlack);
        frame.add(toggleYellow);
        
        
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        
    }

}


 

The Final Result:

Custom Toggle Buttons In Java

Create Custom Toggle Buttons In Java






Java Combobox With Checkbox Items

How to Add CheckBoxes to a Combobox In Java Netbeans

How to Add CheckBoxes to a Combobox In Java Netbeans



In this Java Tutorial we will see How To Create a Custom JCombobox With Checkable Options Using Checkboxes 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.Component;
import java.awt.FlowLayout;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

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

    private CheckComboBoxElement selectedItem; // The currently selected item
    private JComboBox<CheckComboBoxElement> combobox; // JComboBox for the checkable items
    private final JLabel selectedLabel; // JLabel to display the selected item
    
    public CheckComboBox(){
        
        setTitle("Check Combobox");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        
        combobox = new JComboBox<>();
        // Set custom renderer for the combo box
        combobox.setRenderer(new CheckComboBoxRenderer());
        // Add three checkable items to the combo box
        combobox.addItem(new CheckComboBoxElement("ABCD", true)); // Default selection
        combobox.addItem(new CheckComboBoxElement("EFGH", false));
        combobox.addItem(new CheckComboBoxElement("IJKL", false));
        
        // Set the first item as the default selection
        selectedItem = combobox.getItemAt(0);
        selectedItem.setSelected(true);
        
        // Add an item listener to handle item state changes
        combobox.addItemListener((e) -> {
           
            CheckComboBoxElement newItem = (CheckComboBoxElement) combobox.getSelectedItem();
           // Deselect the previously selected item
            if(selectedItem != null){
                selectedItem.setSelected(false);
            }
            // Select the newly selected item and update the reference
            if(newItem != null){
                newItem.setSelected(true);
                selectedItem = newItem;
            }
            
            updateSelectedLabel();
            combobox.repaint();
            
        });
        
        add(combobox);
        selectedLabel = new JLabel("Selected Item: " + selectedItem.getLabel());
        add(selectedLabel);
        
        setSize(300, 200);
        setLocationRelativeTo(null);
        
        
    }
    
    
    // Method to update the selected item label
    private void updateSelectedLabel(){
        selectedLabel.setText("Selected Item: " + (selectedItem != null ? selectedItem.getLabel() : ""));
    }
    
    
    
    
    // Static nested class representing the checkable items in the combo box
    public static class CheckComboBoxElement{
        private final String label;     // Label for the item
        private boolean selected;       // Selection state of the item
        
        // Constructor for the checkable item
        public CheckComboBoxElement(String label, boolean selected)
        {
            this.label = label;
            this.selected = selected;
        }
        
        // Getters And Setters
        public String getLabel(){ return label;}
        
        public boolean isSelected(){ return selected;}
        
        public void setSelected(boolean selected){ this.selected = selected; } 
        
    }
    
    
    
    // Static nested class representing the custom renderer for the combobox
    private class CheckComboBoxRenderer extends JCheckBox implements ListCellRenderer<CheckComboBoxElement>{

        @Override
        public Component getListCellRendererComponent(JList<? extends CheckComboBoxElement> list, CheckComboBoxElement value, int index, boolean isSelected, boolean cellHasFocus) {
            
            setEnabled(list.isEnabled());
            setSelected(value.isSelected());
            setText(value.getLabel());
            
            // Set background and foreground based on selection state
            if(isSelected){
                setBackground(list.getSelectionBackground());
                setForeground(list.getSelectionForeground());
            }
            else{
                setBackground(list.getBackground());
                setForeground(list.getForeground());
            }
            
            return this; // Return the renderer component
            
        }
        
    }
    
    public static void main(String[] args) {
        
        CheckComboBox frame = new CheckComboBox();
        frame.setVisible(true);
        
    }
    
    
}


The Final Result:

Java Combobox With Checkboxes








Java JTable With JTextArea Column

How to Create JTextArea Inside JTable Cells In Java Netbeans

Create a JTable with a JTextArea Column in Java Swing




In this Java Tutorial we will see How To Create a JTable with a JTextArea column to display multiline text in the table cell.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:



package new_tutorials;

import com.formdev.flatlaf.FlatIntelliJLaf;
import java.awt.Component;
import java.util.List;
import java.util.ArrayList;
import javax.swing.AbstractCellEditor;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;

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

    public JtableWithJtextAreaColumn()
    {
        setTitle("JTable With JtextArea Column");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 400);
        setLocationRelativeTo(null);
        /*
        try{
            UIManager.setLookAndFeel(new FlatIntelliJLaf());
        }catch(UnsupportedLookAndFeelException ex){}
        */
        
        initializeGUI();
    }
    
    
    private void initializeGUI()
    {
        JTable table = new JTable(new CustomTableModel());
        table.setRowHeight(60);
        table.setShowHorizontalLines(true);
        table.setShowVerticalLines(true);
        table.getColumnModel().getColumn(3).setCellRenderer(new JTextAreaCellRenderer());
        table.getColumnModel().getColumn(3).setCellEditor(new JTextAreaCellEditor());
        
        JScrollPane scrollpane = new JScrollPane(table);
        add(scrollpane);
        
        setVisible(true);
    }
    
    
    public static void main(String[] args) {
        
        new JtableWithJtextAreaColumn();
        
    }
    
    
    // Custom Table Model for the JTable
    private class CustomTableModel extends AbstractTableModel
    {
        private final String[] columnNames = {"First Name","Last Name","Age","Address"};
        private final List<Person> data = new ArrayList<>();
        
        public CustomTableModel()
        {
            data.add(new Person("John", "Silva", 30, "123 Main St, City A, Country X, Postal Code: 12345, 456 Elm St, City B, Country Y, Postal Code: 56789 - 123 Main St, City A, Country X, Postal Code: 12345, 456 Elm St, City B, Country Y, Postal Code: 56789 - 123 Main St, City A, Country X, Postal Code: 12345, 456 Elm St, City B, Country Y, Postal Code: 56789 - 123 Main St, City A, Country X, Postal Code: 12345, 456 Elm St, City B, Country Y, Postal Code: 56789 - 123 Main St, City A, Country X, Postal Code: 12345, 456 Elm St, City B, Country Y, Postal Code: 56789 - 123 Main St, City A, Country X, Postal Code: 12345, 456 Elm St, City B, Country Y, Postal Code: 56789"));
            data.add(new Person("Jane", "Doe", 25, "456 Elm St, City B, Country Y, Postal Code: 56789"));
            data.add(new Person("Michael", "Johnson", 40, "789 Oak St, City C, Country Z, Postal Code: 10111"));
            data.add(new Person("Emily", "Smith", 28, "321 Pine St, City D, Country X, Postal Code: 67890"));
            data.add(new Person("Daniel", "Brown", 35, "567 Cedar St, City E, Country Y, Postal Code: 11223"));
            data.add(new Person("Olivia", "Jones", 22, "876 Maple St, City F, Country Z, Postal Code: 44556"));
            data.add(new Person("David", "Martinez", 33, "234 Birch St, City G, Country X, Postal Code: 78901"));
            data.add(new Person("Sophia", "Taylor", 29, "987 Willow St, City H, Country Y, Postal Code: 23456"));
            data.add(new Person("William", "Clark", 45, "543 Rose St, City I, Country Z, Postal Code: 11234"));
            data.add(new Person("Emma", "Anderson", 27, "210 Sunflower St, City J, Country X, Postal Code: 56789"));
        }

        @Override
        public int getRowCount() { return data.size();}

        @Override
        public int getColumnCount() { return columnNames.length;}
        
        @Override
        public String getColumnName(int columnIndex){ return columnNames[columnIndex];}

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
           
            Person person = data.get(rowIndex);
            return switch(columnIndex){
                case 0 -> person.getFirstName();
                    case 1 -> person.getLastName();
                        case 2 -> person.getAge();
                            case 3 -> person.getAddress();
                            default -> null;
            };
            
        }
        
        
        public Class<?> getClassName(int columnIndex){
            return columnIndex == 3 ? JTextArea.class:Object.class;
        }
        
        
        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex){
            return columnIndex == 3;
        }
        
        
        @Override
        public void setValueAt(Object value, int rowIndex, int columnIndex){
            
            if(columnIndex == 2 && value instanceof String)
            {
                data.get(rowIndex).setAddress((String)value);
                fireTableCellUpdated(rowIndex, columnIndex);
            }
            
        }
        
    }
    
    
    // Custom cell renderer for JTextArea column
    private class JTextAreaCellRenderer extends DefaultTableCellRenderer
    {
        private final JTextArea textArea;
        
        // Constructor to initialize JTextArea properties
        public JTextAreaCellRenderer()
        {
            textArea = new JTextArea();
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            textArea.setOpaque(true);
        }
        
        // Method to render JTextArea component in table cell
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
        {
            textArea.setText(value != null ? value.toString() : "");
            return textArea;
        }
        
    }  
    
    // Custom cell editor for JTextArea column
    private class JTextAreaCellEditor extends AbstractCellEditor implements TableCellEditor
    {
        private final JTextArea textArea;
        private final JScrollPane scrollPane;
        
        public JTextAreaCellEditor()
        {
            textArea = new JTextArea();
            textArea.setLineWrap(true);
            textArea.setWrapStyleWord(true);
            scrollPane = new JScrollPane(textArea);
            scrollPane.setBorder(null);
        }

        // Method to retrieve the edited cell value
        @Override
        public Object getCellEditorValue() {
           return textArea.getText();
        }

        // Method to return the JTextArea component for editing
        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            
            textArea.setText(value != null ? value.toString() : "");
            return scrollPane;
            
        }
    }
    
    
// Model class representing a person's information
    private class Person 
    {
        private String firstName;
        private String lastName;
        private int age;
        private String address;
        
        public Person(String fname, String lname, int age, String adrs){
            this.firstName = fname;
            this.lastName = lname;
            this.age = age;
            this.address = adrs;
        }

        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public int getAge() {
            return age;
        }

        public String getAddress() {
            return address;
        }
        
        public void setAddress(String address){ this.address = address; }
        
        
    }
    
}


The Final Result:

JTable with JTextArea Cells in Java