Affichage des articles dont le libellé est button. Afficher tous les articles
Affichage des articles dont le libellé est button. Afficher tous les articles

Java Combobox With Buttons

How to Add Buttons to a Combobox In Java Netbeans

How to Add Buttons to a Combobox In Java Netbeans


In this Java Tutorial we will see How To Create a JCombobox With Buttons Inside It 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 java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

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

    private ButtonComboboxElement selectedItem;
    private JComboBox<ButtonComboboxElement> comboBox;
    private final JLabel selectedLabel;
    
    
    public ButtonsComboboxFrame(){
        
        // set up the frame
        setTitle("Buttons-Combobox");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        
        // create the combobox
        comboBox = new JComboBox<>();
        // set the renderer to the combobox
        comboBox.setRenderer(new ButtonComboboxRenderer());
        // add items to the combobox
        comboBox.addItem(new ButtonComboboxElement("Apple", true));
        comboBox.addItem(new ButtonComboboxElement("Tomato", false));
        comboBox.addItem(new ButtonComboboxElement("Orange", false));
        comboBox.addItem(new ButtonComboboxElement("Potato", false));
        comboBox.addItem(new ButtonComboboxElement("Banana", false));
        
        // Set the first item as the default selection
        selectedItem = (ButtonComboboxElement) comboBox.getItemAt(0);
        selectedItem.setSelected(true);
        
        // Add an item listener to handle item state changes
        comboBox.addItemListener((e) -> {
           
            ButtonComboboxElement newElement = (ButtonComboboxElement) comboBox.getSelectedItem();
            
            if(selectedItem != null){ selectedItem.setSelected(false); }
            
            if(newElement != null){ 
                newElement.setSelected(true);
                selectedItem = newElement;
            }
            
            // Update the selected label and repaint the combo box
            updateSelectedLabel();
            comboBox.repaint();
        });
        
        add(comboBox);
        selectedLabel = new JLabel("Selected Item: " + selectedItem.getLabel());
        add(selectedLabel);
        setSize(300,300);
        setLocationRelativeTo(null);
        
    }
    
    // Method to update the selected label text
    public void updateSelectedLabel(){
        selectedLabel.setText("Selected Item: " + (selectedItem != null ? selectedItem.getLabel() : ""));
    }
    
    
    
    // Inner class representing an element in the combobox
    public static class ButtonComboboxElement{
        private final String label;
        private boolean selected;
        
        // Constructor
        public ButtonComboboxElement(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;
        }
        
    }
    
    // Inner class serving as the renderer for the combobox items
    private class ButtonComboboxRenderer extends JButton implements ListCellRenderer<ButtonComboboxElement>{

        private final int BUTTON_MARGIN = 5;
        
        public ButtonComboboxRenderer(){
            setMargin(new Insets(BUTTON_MARGIN, BUTTON_MARGIN, BUTTON_MARGIN, BUTTON_MARGIN));
        }
        
        
        @Override
        public Component getListCellRendererComponent(JList<? extends ButtonComboboxElement> list, ButtonComboboxElement value, int index, boolean isSelected, boolean cellHasFocus) {
            
            setEnabled(list.isEnabled());
            setText(value.getLabel());
            
            return this;
        }
        
    }
    
    
    public static void main(String[] args) {
        ButtonsComboboxFrame frame = new ButtonsComboboxFrame();
        frame.setVisible(true);
    }
}
  
  
    

The Final Result:

Java ComboBox with BUTTONS






Java - Create Rounded Buttons

How to Create and Design Rounded Button In Java Netbeans

How to Create a Rounded JButton Using Java Swing


In this Java Tutorial we will see How To Create two rounded Jbuttons, and clicking each button will trigger a message dialog.
The rounded buttons have a gradient-colored background

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.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.plaf.basic.BasicButtonUI;

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

    public RoundedButtonFrame(){
        
        setTitle("Rounded Button Frame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400,150);
        setLocationRelativeTo(null);
        initializeUI();
    }
    
    private void initializeUI(){
        
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.CENTER,20,40));
        
        RoundedButton button1 = new RoundedButton("Button 1");
        button1.setBackground(new Color(255,69,96));
        
        RoundedButton button2 = new RoundedButton("Button 2");
        button2.setBackground(new Color(70,130,180));
        
        button1.addActionListener((e) -> {
            JOptionPane.showMessageDialog(this, "Button 1 Clicked");
        });
        
        button2.addActionListener((e) -> {
            JOptionPane.showMessageDialog(this, "Button 2 Clicked");
        });
        
        panel.add(button1);
        panel.add(button2);
        
        add(panel);
        
    }
    
    public static void main(String[] args) {
        RoundedButtonFrame frame = new RoundedButtonFrame();
        frame.setVisible(true);
    }

}


// Create a custom JButton class for rounded buttons
class RoundedButton extends JButton{
    
    public RoundedButton(String text){
        
        super(text);
        setUI(new RoundedButtonUI());
        setFont(new Font("Arial",Font.BOLD, 16));
        setForeground(Color.WHITE);
        setCursor(new Cursor(Cursor.HAND_CURSOR));
        
    }
    
}


// Create a custom UI class for rendering rounded buttons
class RoundedButtonUI extends BasicButtonUI{
    
    @Override
    public void installUI(JComponent c){
        super.installUI(c);
        AbstractButton button = (AbstractButton) c;
        
        button.setOpaque(false);
        button.setBorderPainted(false);
    }
    
    
    @Override
    protected void paintText(Graphics g, JComponent c, Rectangle textRect, String text){
        super.paintText(g, c, textRect, text);
    }
    
    
    @Override
    public void paint(Graphics g, JComponent c){
        AbstractButton btn = (AbstractButton) c;
        // Paint the background with rounded corners
        paintBackground(g, btn, btn.getModel().isPressed() ? 2 : 0);
        super.paint(g, c);
    }
    
    // Method to paint the background with rounded corners
    private void paintBackground(Graphics g, JComponent c, int yOffset){
        
        Dimension size = c.getSize();
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
     
        // Fill a rounded rectangle with a darker color
        GradientPaint gradientPaint = new GradientPaint(0, yOffset, c.getBackground().brighter(), 0,size.height - yOffset,c.getBackground().darker());
        g2d.setPaint(gradientPaint);
        g2d.fillRoundRect(0, yOffset, size.width, size.height - yOffset, 25, 25);
        g2d.dispose();
    }
    
}



The Final Result:

Java Rounded Button




Java JTable With Custom Columns

How to Create a JTable with Custom Columns In Java Netbeans

Create JTable With RadioButton, CheckBox, ComboBox, Spinner, TextField and Button Columns In Java Netbeans


In this Java Tutorial we will see How To Create a JTable with custom components in each cell. The table has six columns: RadioButton, CheckBox, ComboBox, Spinner, TextField, and Button.
For each column in the table, custom renderers and editors are set using the setColumnRendererAndEditor method. 
This method associates a TableCellRenderer (for rendering cell content) and a TableCellEditor (for editing cell content) with a specific column in the table.
The getJobList Method: Returns an array of job titles. This array is used to populate the ComboBox in the third column.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.






Project Source Code:

RadioButtonRenderer Class:

public class RadioButtonRenderer extends JRadioButton implements TableCellRenderer{

    public RadioButtonRenderer(){
        setHorizontalAlignment(SwingConstants.CENTER);
        setOpaque(false);
    }
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
     
        // Set the selected state based on the value
        setSelected(value != null && (boolean)value);
        return this;
    
    }

}


RadioButtonEditor Class:

public class RadioButtonEditor extends AbstractCellEditor implements TableCellEditor{

    private final JRadioButton button;
    
    public RadioButtonEditor(){
        button = new JRadioButton();
        button.setHorizontalAlignment(SwingConstants.CENTER);
    }
    
    
    @Override
    public Object getCellEditorValue() {
    
        // retun the value of the radiobutton
        return button.isSelected();
        
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    
        // Set the selected state based on the value
        button.setSelected(value != null && (boolean)value);
        return button;
        
    }

    
}


JTable With RadioButton Column





CheckBoxRenderer Class:

public class CheckBoxRenderer extends DefaultTableCellRenderer{

    private final JCheckBox checkBox = new JCheckBox();
    
    public CheckBoxRenderer(){
        checkBox.setHorizontalAlignment(SwingConstants.CENTER);
    }
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
     
        // Set the selected state based on the value
        checkBox.setSelected(value != null && (boolean)value);
        return checkBox;
    
    }
    
}


CheckBoxEditor Class:

public class CheckBoxEditor extends AbstractCellEditor implements TableCellEditor{

    private final JCheckBox checkBox = new JCheckBox();
    
    public CheckBoxEditor(){
        checkBox.setHorizontalAlignment(SwingConstants.CENTER);
    }
    
    @Override
    public Object getCellEditorValue() {
    
        // retun the value of the checkbox
        return checkBox.isSelected();
        
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    
        // Set the selected state based on the value
        checkBox.setSelected((boolean)value);
        return checkBox;
        
    }
    
}


JTable With CheckBox Column





ComboboxRenderer Class:

public class ComboboxRenderer extends JComboBox<String> implements TableCellRenderer{

    public ComboboxRenderer(String[] items){ super(items); }
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
     
        // Set the selected item in the JComboBox based on the cell value
        setSelectedItem(value);
        
        // Ensure the JComboBox is focused before rendering
        if(hasFocus){ requestFocusInWindow(); } 
        
        return this;
    }

}



ComboboxEditor Class:

public class ComboboxEditor extends DefaultCellEditor{

    public ComboboxEditor(String[] items){ 
        super(new JComboBox<>(items)); 
        // Set the number of clicks needed to start editing
        setClickCountToStart(0);
    }
    
    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
     
         // Set the selected item in the JComboBox based on the cell value
         ((JComboBox<?>) editorComponent).setSelectedItem(value);
         
         // Ensure the JComboBox is focused before editing
         SwingUtilities.invokeLater(() -> {
             ((JComboBox<?>) editorComponent).requestFocusInWindow();
         });
        
         return editorComponent;
    }
    
    
    @Override
    public Object getCellEditorValue(){
        // Return the selected item from the JComboBox
        return ((JComboBox<?>) editorComponent).getSelectedItem();
    }
  
}


JTable With ComboBox Column





SpinnerRenderer Class:

public class SpinnerRenderer extends JSpinner implements TableCellRenderer{
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    
        // set value of the spinner
        setValue(value);
        return this;
    
    }

}



SpinnerEditor Class:

public class SpinnerEditor extends DefaultCellEditor{

    public SpinnerEditor(JSpinner spinner) {
        // Initialize the spinner editor
        super(new JCheckBox());
        editorComponent = spinner;
        delegate = new EditorDelegate() {
            
            // Set the value of the spinner
            @Override
            public void setValue(Object value){spinner.setValue(value);}
            
            // Get the value of the spinner
            @Override
            public Object getCellEditorValue(){ return spinner.getValue(); }
            
        };
    }
 
}



JTable With Spinner Column





TextFieldRenderer Class:

public class TextFieldRenderer extends JTextField implements TableCellRenderer{

    public TextFieldRenderer(){setHorizontalAlignment(JTextField.CENTER);}

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      
        // Set the text of the text field
        setText(value != null ? value.toString() : "");
        return this;
        
    }
    
}



JTable With TextField Column





ButtonRenderer Class:

public class ButtonRenderer extends JButton implements TableCellRenderer{

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    
        // Set the text of the button
        setText(value != null ? value.toString() : "");
        return this;
        
    }

}




ButtonEditor Class:

public class ButtonEditor extends DefaultCellEditor{

    private JButton button;
    
    public ButtonEditor(JCheckBox checkBox) {
        // Initialize the button editor and add action listener for button click
        super(checkBox);
        button = new JButton();
        button.addActionListener((e) -> {
            JOptionPane.showMessageDialog(button, button.getText() + " Clicked");
        });
        
    }
    
    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        // Set the text of the button
        button.setText(value != null ? value.toString() : "");
        return button;        
    }
    
    // Get the text of the button
    @Override
    public Object getCellEditorValue(){ return button.getText(); }

}



JTable With Button Column





CustomTableModel Class:

public class CustomTableModel extends AbstractTableModel{
    private final Object[][] data;
    private final String[] columnNames;
    
    public CustomTableModel(Object[][] data, String[] columnNames){
        this.data = data;
        this.columnNames = columnNames;
    }
    

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

    @Override
    public int getColumnCount() { return columnNames.length; }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
    
        return data[rowIndex][columnIndex];
        
    }

    @Override
    public String getColumnName(int column){ return columnNames[column]; }
    
    @Override
    public Class<?> getColumnClass(int column){ return data[0][column].getClass(); }
    
    @Override
    public boolean isCellEditable(int row, int column){ return true; }
    
    @Override
    public void setValueAt(Object value, int row, int column){
        // Update the data and notify listeners of the change
        data[row][column] = value;
        fireTableCellUpdated(row, column);
    }
    
    
}






The MainClass Class:

public class MainClass extends JFrame{

    public MainClass(){
        setTitle("Table Custom Component");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        CustomTableModel model = new CustomTableModel(
                new Object[][]{
                        {false, false, "Developer", 1, "Text 1", "Button 1"},
                        {false, true, "Designer", 2, "Text 2", "Button 2"},
                        {true, false, "Manager", 3, "Text 3", "Button 3"},
                        {true, false, "Engineer", 4, "Text 4", "Button 4"}
                },
                new String[]{"RadioButton", "CheckBox", "ComboBox", "Spinner", "TextField", "Button"}
        );
        
        
        JTable table = new JTable(model);
        table.setRowHeight(40);
        
        setColumnRendererAndEditor(table, 0, new RadioButtonRenderer(), new RadioButtonEditor());
        setColumnRendererAndEditor(table, 1, new CheckBoxRenderer(), new CheckBoxEditor());
        setColumnRendererAndEditor(table, 2, new ComboboxRenderer(getJobList()), new ComboboxEditor(getJobList()));
        setColumnRendererAndEditor(table, 3, new SpinnerRenderer(), new SpinnerEditor(new JSpinner()));
        setColumnRendererAndEditor(table, 4, new TextFieldRenderer(), new DefaultCellEditor(new JTextField()));
        setColumnRendererAndEditor(table, 5, new ButtonRenderer(), new ButtonEditor(new JCheckBox()));
        
        
        JScrollPane scrollPanel = new JScrollPane(table);
        add(scrollPanel);
        setSize(600, 400);
        setLocationRelativeTo(null);
        
    }
    
    
    private void setColumnRendererAndEditor(JTable table, int columnIndex, TableCellRenderer renderer, TableCellEditor editor){
        // Set the renderer and editor for a specific column
        table.getColumnModel().getColumn(columnIndex).setCellRenderer(renderer);
        table.getColumnModel().getColumn(columnIndex).setCellEditor(editor);
    }
    
    
    private String[] getJobList(){
        // Return an array of job titles
        // we will use it to populate the combobox
        return new String[]{"Engineer", "Designer", "Manager", "Developer", "Analyst"};
        
    }
    
    
    public static void main(String[] args) {
        MainClass app = new MainClass();
        app.setVisible(true);
    }
    
}



The Final Result:

Java JTable With Custom Columns


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




disclaimer: you will get the source code, and to make it work in your machine is your responsibility and to debug any error/exception is your responsibility this project is for the students who want to see an example and read the code not to get and run.