0

Is there a way to add dynamically items of type JCheckBox in Java as in JComboBox we use addItem method?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
alessandrob
  • 1,605
  • 4
  • 20
  • 23

2 Answers2

1

Something like this may be effective if you want to add multiple items to another Component:

List<Component>  myList = new Arraylist<Component>() //List for storage
Item myItem = new Item(); //New component
myList.add(myItem);  //Store all the components to add in the list

for(int i = 0; i < myList.size; i++){
myjCheckBox.add(myList[i]); //Add all items from list to jCheckBox
}

The above example uses this method inherited in jCheckBox and should be able to provide what you need

Hope it helps!

Levenal
  • 3,796
  • 3
  • 24
  • 29
1

JCheckList

Note you might use actual check-boxes for the rendering component, but this was a few lines shorter.

import java.awt.*;
import javax.imageio.ImageIO;
import javax.swing.*;

class JCheckList {

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JPanel gui = new JPanel(new BorderLayout());

                JLabel l = new JLabel("Ctrl/shift click to select multiple");
                gui.add(l, BorderLayout.PAGE_START);

                JList<String> list = new JList<String>(
                        ImageIO.getReaderFileSuffixes());
                list.setCellRenderer(new CheckListCellRenderer());
                gui.add(list, BorderLayout.CENTER);

                JOptionPane.showMessageDialog(null, gui);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
        SwingUtilities.invokeLater(r);
    }
}

class CheckListCellRenderer extends DefaultListCellRenderer {

    String checked = new String(Character.toChars(9745));
    String unchecked = new String(Character.toChars(9746));

    @Override
    public Component getListCellRendererComponent(
            JList list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus) {
        Component c = super.getListCellRendererComponent(
                list,value,index,isSelected,cellHasFocus);
        if (c instanceof JLabel) {
            JLabel l = (JLabel)c;
            String s = (isSelected ? checked : unchecked) + (String)value;
            l.setText(s);
        }

        return c;
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433