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





Python Tkinter Sonic Wave Animation

How to Create a Sonic Wave Animation in Python Tkinter

How to Create a Sonic Wave Animation in Python Tkinter


In this Python Tutorial we will see How to Create a Sonic Wave animation that features animated bars with dynamic colors, glow effects, and smooth sine wave motion Using Python Tkinter.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter (GUI).
- VS Editor.






Project Source Code:




import tkinter as tk
import math
import time
import colorsys

class SonicWave(tk.Canvas):

def __init__(self, master=None, **kwargs):
# Configuration
self.BAR_COUNT = 7
self.BAR_WIDTH = 5
self.BAR_GAP = 10
self.BAR_HEIGHT = 65
self.ANIMATION_DELAY = 1500 # milliseconds for full cycle

# Dark background color
bg_color = "#111122"

# Set canvas dimensions
width = self.BAR_COUNT * (self.BAR_WIDTH + self.BAR_GAP) + 40
height = self.BAR_HEIGHT + 60

# Initialize the canvas with our background color
super().__init__(master, width=width, height=height, bg=bg_color,
highlightthickness=0, **kwargs)

# Define colors
self.colors = [
"#00eeff", # blue
"#b300ff", # purple
"#ff00ff", # pink
"#0aff0a", # green
"#ff3300" # orange
]

# Initialize bar heights and animation state
self.bar_heights = [0.2] * self.BAR_COUNT
self.hue_shift = 0.0

# Start the animation
self.is_running = True
self.animate()


def get_color_with_shift(self, base_color, offset=0):
"""Apply a hue shift to a color for dynamic color effects"""
# Convert hex to RGB
r = int(base_color[1:3], 16) / 255.0
g = int(base_color[3:5], 16) / 255.0
b = int(base_color[5:7], 16) / 255.0

# Convert RGB to HSV
h, s, v = colorsys.rgb_to_hsv(r, g, b)
# Apply the hue shift
h = (h + self.hue_shift + offset) % 1.0
# Convert back to RGB
r, g, b = colorsys.hsv_to_rgb(h, s, v)

# Convert to hex
return f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}"

def animate(self):
"""Main animation loop"""
if not self.is_running:
return

self.update_bar_heights()
self.draw_spinner()

# Schedule the next animation frame
self.after(30, self.animate)


def update_bar_heights(self):
"""Update the heights of each bar based on a sine wave function"""
current_time = time.time() * 1000 # Convert to milliseconds

# Update each bar's height based on sine wave function
for i in range(self.BAR_COUNT):
# Calculate phase offset for each bar
phase_offset = i * (math.pi / 8)

# Use sine wave to animate heights (0.2 to 1.0 range)
progress = (current_time % self.ANIMATION_DELAY) / self.ANIMATION_DELAY
angle = 2 * math.pi * progress + phase_offset
self.bar_heights[i] = 0.2 + 0.8 * abs(math.sin(angle))

# Gradually shift the hue
self.hue_shift = (self.hue_shift + 0.005) % 1.0




def create_text_shadow(self, x, y, text, font_config):
# Create shadow text (slight offset, darker color)
shadow_color = "#555555"
self.create_text(x+2, y+2, text=text, fill=shadow_color, font=font_config)

# Create main text with a fixed color
main_color = "#FFFFFF" # Use white color
self.create_text(x, y, text=text, fill=main_color, font=font_config)



def draw_spinner(self):
"""Draw the spinner with visual elements"""
# Clear the canvas
self.delete("all")

# Calculate layout dimensions
total_width = self.BAR_COUNT * (self.BAR_WIDTH + self.BAR_GAP) - self.BAR_GAP
start_x = (self.winfo_width() - total_width) // 2
base_y = (self.winfo_height() + self.BAR_HEIGHT) // 2 - 10

# Draw "SONIC WAVE" text label
# Ensure the text is positioned in a visible area
text_y = min(base_y + self.BAR_HEIGHT // 2 + 20, self.winfo_height() - 20)
self.create_text_shadow(
self.winfo_width() // 2,
text_y,
"SONIC WAVE",
("Arial", 13, "bold")
)

# Draw bars
for i in range(self.BAR_COUNT):
x = start_x + i * (self.BAR_WIDTH + self.BAR_GAP)
height = int(self.bar_heights[i] * self.BAR_HEIGHT)
y = base_y - height

# Get color based on current animation state with dynamic hue shifting
bar_color = self.get_color_with_shift(self.colors[i % len(self.colors)],
i * 0.05)

# Draw the bar
self.create_rectangle(
x, y, x + self.BAR_WIDTH, base_y,
fill=bar_color, outline="", width=0
)
# Create a glow effect by drawing multiple rectangles
for j in range(1, 5):
# Create outlines for glow effect
self.create_rectangle(
x - j, y - j, x + self.BAR_WIDTH + j, base_y + j,
outline=bar_color, width=1
)

def stop_animation(self):
"""Method to stop the animation when no longer needed"""
self.is_running = False



class AppFrame(tk.Frame):
"""A frame to hold the spinner with UI elements"""

def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
self.config(bg="#0d0d18", padx=25, pady=25)
self.pack(fill=tk.BOTH, expand=True)

# Create a background
self.create_background()

# Add the spinner
self.spinner = SonicWave(self)
self.spinner.pack(pady=10)

# Add a version or title or any text label
version_label = tk.Label(
self,
text="v2.0",
bg="#0d0d18",
fg="#444444",
font=("Arial", 8)
)
version_label.pack(side=tk.BOTTOM, anchor=tk.SE, padx=5, pady=5)

def create_background(self):
"""Create a background frame"""
gradient_frame = tk.Frame(self, width=300, height=250, bg="#0d0d18")
gradient_frame.place(x=0, y=0, relwidth=1, relheight=1)





def main():
root = tk.Tk()
root.title("Sonic Wave")

# Set dark theme for the window
root.configure(bg="#0a0a14")

# Create our app frame
app_frame = AppFrame(root)

# Set window size and position
root.geometry("300x250")
root.eval('tk::PlaceWindow . center') # Center the window

# Make the window non-resizable for consistent layout
root.resizable(False, False)

# Handle window close event
def on_closing():
app_frame.spinner.stop_animation()
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)

# Start the main event loop
root.mainloop()


if __name__ == "__main__":
main()



The Final Result:

Python Tkinter Sonic Wave Animation 1

Python Tkinter Sonic Wave Animation 2

Python Tkinter Sonic Wave Animation 3