<p>What would be the best way to have a list of items with a checkbox each in Java Swing?</p>

<p>I.e. a JList with items that have some text and a checkbox each?</p>

[{'answer_id': 19796, 'author': 'ninesided', 'author_id': 1030, 'author_profile': 'https://Stackoverflow.com/users/1030', 'pm_score': 4, 'selected': False, 'text': '<p>I\'d probably be looking to use a <em>JTable</em> rather than a <em>JList</em> and since the default rendering of a checkbox is rather ugly, I\'d probably be looking to drop in a custom <em>TableModel</em>, <em>CellRenderer</em> and <em>CellEditor</em> to represent a boolean value. Of course, I would imagine this has been done a bajillion times already. Sun has <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/table.html" rel="noreferrer">good examples</a>.</p>\n'}, {'answer_id': 19804, 'author': 'Telcontar', 'author_id': 518, 'author_profile': 'https://Stackoverflow.com/users/518', 'pm_score': 5, 'selected': True, 'text': '<p>Create a custom <code>ListCellRenderer</code> and asign it to the <code>JList</code>.</p>\n\n<p>This custom <code>ListCellRenderer</code> must return a <code>JCheckbox</code> in the implementantion of <code>getListCellRendererComponent(...)</code> method.</p>\n\n<p>But this <code>JCheckbox</code> will not be editable, is a simple paint in the screen is up to you to choose when this <code>JCheckbox</code> must be \'ticked\' or not, </p>\n\n<p>For example, show it ticked when the row is selected (parameter <code>isSelected</code>), but this way the check status will no be mantained if the selection changes. Its better to show it checked consulting the data below the <code>ListModel</code>, but then is up to you to implement the method who changes the check status of the data, and notify the change to the <code>JList</code> to be repainted.</p>\n\n<p>I Will post sample code later if you need it</p>\n\n<p><a href="http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html" rel="noreferrer">ListCellRenderer</a></p>\n'}, {'answer_id': 19840, 'author': 'basszero', 'author_id': 287, 'author_profile': 'https://Stackoverflow.com/users/287', 'pm_score': 2, 'selected': False, 'text': '<p>Odds are good w/ Java that someone has already implemented the widget or utility you need. Part of the benefits of a large OSS community. No need to reinvent the wheel unless you really want to do it yourself. In this case it would be a good learning exercise in CellRenderers and Editors.</p>\n\n<p>My project has had great success with JIDE. The component you want, a Check Box List, is in the JIDE Common Layer (which is OSS and hosted on java.net). The commercial stuff is good too, but you don\'t need it.</p>\n\n<p><a href="http://www.jidesoft.com/products/oss.htm" rel="nofollow noreferrer">http://www.jidesoft.com/products/oss.htm</a>\n<a href="https://jide-oss.dev.java.net/" rel="nofollow noreferrer">https://jide-oss.dev.java.net/</a></p>\n'}, {'answer_id': 1966151, 'author': 'Dan Rosenstark', 'author_id': 8047, 'author_profile': 'https://Stackoverflow.com/users/8047', 'pm_score': 5, 'selected': False, 'text': '<p>A wonderful answer is this <a href="http://www.devx.com/tips/Tip/5342" rel="noreferrer"><code>CheckBoxList</code></a>. It implements Telcontar\'s answer (though 3 years before :)... I\'m using it in Java 1.6 with no problems. I\'ve also added an <code>addCheckbox</code> method like this (surely could be shorter, haven\'t used Java in a while):</p>\n\n<pre><code>public void addCheckbox(JCheckBox checkBox) {\n    ListModel currentList = this.getModel();\n    JCheckBox[] newList = new JCheckBox[currentList.getSize() + 1];\n    for (int i = 0; i &lt; currentList.getSize(); i++) {\n        newList[i] = (JCheckBox) currentList.getElementAt(i);\n    }\n    newList[newList.length - 1] = checkBox;\n    setListData(newList);\n}\n</code></pre>\n\n<p>I tried out the demo for the Jidesoft stuff, playing with the <code>CheckBoxList</code> I encountered some problems (behaviors that didn\'t work). I\'ll modify this answer if I find problems with the <code>CheckBoxList</code> I linked to.</p>\n'}, {'answer_id': 18803557, 'author': 'Zero_8', 'author_id': 2779549, 'author_profile': 'https://Stackoverflow.com/users/2779549', 'pm_score': 2, 'selected': False, 'text': '<p>I recommend you use a JPanel with a GridLayout of 1 column. Add the checkBoxes to the JPanel, and set the JPanel as the data source of a JScrollPane. And to get the selected CheckBoxes, just call the getComponents() of the JPanel to get the CheckBoxes.</p>\n'}, {'answer_id': 24777687, 'author': 'Rawa', 'author_id': 1724097, 'author_profile': 'https://Stackoverflow.com/users/1724097', 'pm_score': 3, 'selected': False, 'text': '<h2>Better solution for Java 7 and newer</h2>\n\n<p>I stumbled upon this question and realized that some of the answers are pretty old and outdated. Nowadays, JList is generic and thus there are better solutions.</p>\n\n<p>My solution of the generic JCheckBoxList:</p>\n\n<pre><code>import java.awt.Component;\n\nimport javax.swing.*;\nimport javax.swing.border.*;\n\nimport java.awt.event.*;\n\n@SuppressWarnings("serial")\npublic class JCheckBoxList extends JList&lt;JCheckBox&gt; {\n  protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);\n\n  public JCheckBoxList() {\n    setCellRenderer(new CellRenderer());\n    addMouseListener(new MouseAdapter() {\n      public void mousePressed(MouseEvent e) {\n        int index = locationToIndex(e.getPoint());\n        if (index != -1) {\n          JCheckBox checkbox = (JCheckBox) getModel().getElementAt(index);\n          checkbox.setSelected(!checkbox.isSelected());\n          repaint();\n        }\n      }\n    });\n    setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n  }\n\n  public JCheckBoxList(ListModel&lt;JCheckBox&gt; model){\n    this();\n    setModel(model);\n  }\n\n  protected class CellRenderer implements ListCellRenderer&lt;JCheckBox&gt; {\n    public Component getListCellRendererComponent(\n        JList&lt;? extends JCheckBox&gt; list, JCheckBox value, int index,\n        boolean isSelected, boolean cellHasFocus) {\n      JCheckBox checkbox = value;\n\n      //Drawing checkbox, change the appearance here\n      checkbox.setBackground(isSelected ? getSelectionBackground()\n          : getBackground());\n      checkbox.setForeground(isSelected ? getSelectionForeground()\n          : getForeground());\n      checkbox.setEnabled(isEnabled());\n      checkbox.setFont(getFont());\n      checkbox.setFocusPainted(false);\n      checkbox.setBorderPainted(true);\n      checkbox.setBorder(isSelected ? UIManager\n          .getBorder("List.focusCellHighlightBorder") : noFocusBorder);\n      return checkbox;\n    }\n  }\n}\n</code></pre>\n\n<p>For dynamically adding JCheckBox lists you need to create your own ListModel or add the DefaultListModel.</p>\n\n<pre><code>DefaultListModel&lt;JCheckBox&gt; model = new DefaultListModel&lt;JCheckBox&gt;();\nJCheckBoxList checkBoxList = new JCheckBoxList(model);\n</code></pre>\n\n<p>The <a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/DefaultListModel.html" rel="noreferrer">DefaultListModel</a> are generic and thus you can use methods specified by JAVA 7 API <a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/DefaultListModel.html" rel="noreferrer">here</a> like this:</p>\n\n<pre><code>model.addElement(new JCheckBox("Checkbox1"));\nmodel.addElement(new JCheckBox("Checkbox2"));\nmodel.addElement(new JCheckBox("Checkbox3"));\n</code></pre>\n'}, {'answer_id': 25521015, 'author': 'Željko Vuković', 'author_id': 3980145, 'author_profile': 'https://Stackoverflow.com/users/3980145', 'pm_score': 0, 'selected': False, 'text': '<p>Here is just a little addition to the JCheckBoxList by Rawa. This will add the ability to select using space bar. If multiple items are selected, all will be set to inverted value of the first item.</p>\n\n<pre><code>        addKeyListener(new KeyAdapter() {\n        @Override\n        public void keyPressed(KeyEvent e) {\n            int index = getSelectedIndex();\n            if (index != -1 &amp;&amp; e.getKeyCode() == KeyEvent.VK_SPACE) {\n                boolean newVal = !((JCheckBox) (getModel()\n                        .getElementAt(index))).isSelected();\n                for (int i : getSelectedIndices()) {\n                    JCheckBox checkbox = (JCheckBox) getModel()\n                            .getElementAt(i);\n                    checkbox.setSelected(newVal);\n                    repaint();\n                }\n            }\n        }\n        });\n</code></pre>\n'}, {'answer_id': 27215934, 'author': 'René Link', 'author_id': 974186, 'author_profile': 'https://Stackoverflow.com/users/974186', 'pm_score': 4, 'selected': False, 'text': '<p>Just implement a <code>ListCellRenderer</code></p>\n\n<pre><code>public class CheckboxListCellRenderer extends JCheckBox implements ListCellRenderer {\n\n    public Component getListCellRendererComponent(JList list, Object value, int index, \n            boolean isSelected, boolean cellHasFocus) {\n\n        setComponentOrientation(list.getComponentOrientation());\n        setFont(list.getFont());\n        setBackground(list.getBackground());\n        setForeground(list.getForeground());\n        setSelected(isSelected);\n        setEnabled(list.isEnabled());\n\n        setText(value == null ? "" : value.toString());  \n\n        return this;\n    }\n}\n</code></pre>\n\n<p>and set the renderer</p>\n\n<pre><code>JList list = new JList();\nlist.setCellRenderer(new CheckboxListCellRenderer());\n</code></pre>\n\n<p>this will result in</p>\n\n<p><img src="https://i.stack.imgur.com/pO1lh.png" alt="CheckboxListCellRenderer example"></p>\n\n<p>Details at <a href="http://www.link-intersystems.com/blog/2014/10/19/custom-swing-component-renderers/" rel="noreferrer">Custom swing component renderers</a>.</p>\n\n<p>PS: If you want radio elements just replace <code>extends JCheckbox</code> with <code>extends JRadioButton</code>.</p>\n'}, {'answer_id': 32712019, 'author': 'Lucky', 'author_id': 1793718, 'author_profile': 'https://Stackoverflow.com/users/1793718', 'pm_score': 1, 'selected': False, 'text': '<p>All of the aggregate components in Swing--that is, components made up other components, such as JTable, JTree, or JComboBox--can be highly customized. For example, a JTable component normally displays a grid of JLabel components, but it can also display JButtons, JTextFields, or even other JTables. Getting these aggregate components to display non-default objects is the easy part, however. Making them respond properly to keyboard and mouse events is a much harder task, due to Swing\'s separation of components into "renderers" and "editors." This separation was (in my opinion) a poor design choice and only serves to complicate matters when trying to extend Swing components.</p>\n\n<p>To see what I mean, try enhancing Swing\'s JList component so that it displays checkboxes instead of labels. According to Swing philosophy, this task requires implementing two interfaces: ListCellRenderer (for drawing the checkboxes) and CellEditor (for handling keyboard and mouse events on the checkboxes). Implementing the ListCellRenderer interface is easy enough, but the CellEditor interface can be rather clumsy and hard to understand. In this particular case, I would suggest forgetting CellEditor entirely and to handle input events directly, as shown in the following code.</p>\n\n<pre><code>import javax.swing.*;\nimport javax.swing.border.*;\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class CheckBoxList extends JList\n{\n   protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);\n\n   public CheckBoxList()\n   {\n      setCellRenderer(new CellRenderer());\n\n      addMouseListener(new MouseAdapter()\n         {\n            public void mousePressed(MouseEvent e)\n            {\n               int index = locationToIndex(e.getPoint());\n\n               if (index != -1) {\n                  JCheckBox checkbox = (JCheckBox)\n                              getModel().getElementAt(index);\n                  checkbox.setSelected(\n                                     !checkbox.isSelected());\n                  repaint();\n               }\n            }\n         }\n      );\n\n      setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n   }\n\n   protected class CellRenderer implements ListCellRenderer\n   {\n      public Component getListCellRendererComponent(\n                    JList list, Object value, int index,\n                    boolean isSelected, boolean cellHasFocus)\n      {\n         JCheckBox checkbox = (JCheckBox) value;\n         checkbox.setBackground(isSelected ?\n                 getSelectionBackground() : getBackground());\n         checkbox.setForeground(isSelected ?\n                 getSelectionForeground() : getForeground());\n         checkbox.setEnabled(isEnabled());\n         checkbox.setFont(getFont());\n         checkbox.setFocusPainted(false);\n         checkbox.setBorderPainted(true);\n         checkbox.setBorder(isSelected ?\n          UIManager.getBorder(\n           "List.focusCellHighlightBorder") : noFocusBorder);\n         return checkbox;\n      }\n   }\n}\n</code></pre>\n\n<p>Here, I intercept mouse clicks from the listbox and simulate a click on the appropriate checkbox. The result is a "CheckBoxList" component that is both simpler and smaller than an equivalent component using the CellEditor interface. To use the class, simply instantiate it, then pass it an array of JCheckBox objects (or subclasses of JCheckBox objects) by calling setListData. Note that the checkboxes in this component will not respond to keypresses (i.e. the spacebar), but you could always add your own key listener if needed.</p>\n\n<p>Source: <a href="http://www.devx.com/tips/Tip/5342" rel="nofollow">DevX.com</a></p>\n'}, {'answer_id': 74432809, 'author': 'huakim', 'author_id': 20501329, 'author_profile': 'https://Stackoverflow.com/users/20501329', 'pm_score': 0, 'selected': False, 'text': '<p>this is yet another example of making list with checkboxes</p>\n<pre><code>class JCheckList&lt;T&gt; extends JList&lt;T&gt; {\n\n    protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);\n\n    public void setSelected(int index) {\n        if (index != -1) {\n            JCheckBox checkbox = (JCheckBox) getModel().getElementAt(index);\n            checkbox.setSelected(\n                    !checkbox.isSelected());\n            repaint();\n        }\n    }\n\n    protected static class CellListener\n            extends DefaultListModel\n            implements ListDataListener {\n\n        ListModel ls;\n\n        public CellListener(ListModel ls) {\n            ls.addListDataListener(this);\n            int i = ls.getSize();\n            for (int v = 0; v &lt; i; v++) {\n                var r = new JCheckBox();\n                r.setText(ls.getElementAt(v).toString());\n                this.addElement(r);\n            }\n            this.ls = ls;\n        }\n\n        @Override\n        public void intervalAdded(ListDataEvent e) {\n            int begin = e.getIndex0();\n            int end = e.getIndex1();\n            for (; begin &lt;= end; begin++) {\n                var r = new JCheckBox();\n                r.setText(ls.getElementAt(begin).toString());\n                this.add(begin, r);\n            }\n        }\n\n        @Override\n        public void intervalRemoved(ListDataEvent e) {\n            int begin = e.getIndex0();\n            int end = e.getIndex1();\n            for (; begin &lt;= end; end--) {\n                this.remove(begin);\n            }\n        }\n\n        @Override\n        public void contentsChanged(ListDataEvent e) {\n\n        }\n    }\n\n    public JCheckList() {\n        setCellRenderer(new CellRenderer());\n\n        addMouseListener(new MouseAdapter() {\n            public void mousePressed(MouseEvent e) {\n                int index = locationToIndex(e.getPoint());\n\n                setSelected(index);\n            }\n        }\n        );\n\n\n    addKeyListener(new KeyListener(){\n        @Override\n        public void keyTyped(KeyEvent e) {\n            \n        }\n\n        @Override\n        public void keyPressed(KeyEvent e) {\n            if (e.getKeyCode() == KeyEvent.VK_SPACE){\n                \n            int index = JCheckList.this.getSelectedIndex();\n\n            setSelected(index);\n            }\n        }\n\n        @Override\n        public void keyReleased(KeyEvent e) {\n            \n        }\n            \n    });\n\n        setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n    }\n\n    @Override\n    public void setModel(ListModel&lt;T&gt; d) {\n        var r = new CellListener(d);\n        d.addListDataListener(r);\n        super.setModel(r);\n    }\n\n    protected class CellRenderer implements ListCellRenderer {\n\n        public Component getListCellRendererComponent(\n                JList list, Object value, int index,\n                boolean isSelected, boolean cellHasFocus) {\n            JCheckBox checkbox = (JCheckBox) value;\n            checkbox.setBackground(isSelected\n                    ? getSelectionBackground() : getBackground());\n            checkbox.setForeground(isSelected\n                    ? getSelectionForeground() : getForeground());\n            checkbox.setEnabled(isEnabled());\n            checkbox.setFont(getFont());\n            checkbox.setFocusPainted(false);\n            checkbox.setBorderPainted(true);\n            checkbox.setBorder(isSelected\n                    ? UIManager.getBorder(\n                            &quot;List.focusCellHighlightBorder&quot;) : noFocusBorder);\n            return checkbox;\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 74535408, 'author': 'JPT', 'author_id': 4308462, 'author_profile': 'https://Stackoverflow.com/users/4308462', 'pm_score': 1, 'selected': False, 'text': '<p>I don\'t like the solutions that put a Checkbox into the model. The model should only contain data not display elements.</p>\n<p>I found this <a href="http://www.java2s.com/Tutorials/Java/Swing_How_to/JList/Create_JList_of_CheckBox.htm" rel="nofollow noreferrer">http://www.java2s.com/Tutorials/Java/Swing_How_to/JList/Create_JList_of_CheckBox.htm</a></p>\n<p>which I optimized a bit. The ACTIVE flag represents the Checkbox, the SELECTED flag shows what entry the cursor sits on.</p>\n<p>my version requires a renderer</p>\n<pre><code>import java.awt.Component;\n\nimport javax.swing.JCheckBox;\nimport javax.swing.JList;\nimport javax.swing.ListCellRenderer;\n\nclass CheckListRenderer extends JCheckBox implements ListCellRenderer&lt;Entity&gt; {\n\n    @Override\n    public Component getListCellRendererComponent(JList&lt;? extends Entity&gt; list, \n        Entity value, int index, boolean isSelected, boolean cellHasFocus) {\n\n            setEnabled(list.isEnabled());\n            setSelected(value.isActive()); // sets the checkbox\n            setFont(list.getFont());\n        if (isSelected) { // highlights the currently selected entry\n            setBackground(list.getSelectionBackground());\n            setForeground(list.getSelectionForeground());\n        } else {\n            setBackground(list.getBackground());\n            setForeground(list.getForeground());\n        }\n        setText(value.toString()+&quot; - A&quot; + value.isActive()+&quot; - F&quot;+cellHasFocus+&quot; - S&quot;+isSelected );\n        return this;\n    }\n\n}\n</code></pre>\n<p>and an entity that got the active field:</p>\n<pre><code>public class Entity {\n\n    private boolean active = true;\n\n    public boolean isActive() {\n        return active;\n    }\n\n    public void setActive(boolean isActive) {\n        this.active = isActive;\n    }\n\n}\n</code></pre>\n<p>Now you only have to add this to your JList:</p>\n<pre><code>list = new JList&lt;Entity&gt;();\nlist.setModel(new DefaultListModel&lt;Entity&gt;());\nlist.setCellRenderer(new CheckListRenderer());\nlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\nlist.addMouseListener(new MouseAdapter() {\n    @Override\n    public void mouseClicked(MouseEvent event) {\n        if (event.getX() &lt; 20) { \n            // Quick and dirty: only change the tick if clicked into the leftmost pixels\n            @SuppressWarnings(&quot;unchecked&quot;)\n            JList&lt;Entity&gt; list = ((JList&lt;Entity&gt;) event.getSource());\n            int index = list.locationToIndex(event.getPoint());// Get index of item clicked\n            if (index &gt;= 0) {\n                Entity item = (Entity) list.getModel().getElementAt(index);\n                item.setActive(!item.isActive()); // Toggle selected state\n                list.repaint(list.getCellBounds(index, index));// Repaint cell\n            }\n        }\n    }\n});\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/19766', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1827/']