{"id":251,"date":"2015-06-30T14:35:49","date_gmt":"2015-06-30T04:35:49","guid":{"rendered":"https:\/\/learn-java-by-example.com\/?p=251"},"modified":"2015-11-06T11:30:41","modified_gmt":"2015-11-06T00:30:41","slug":"add-checkbox-items-jlist","status":"publish","type":"post","link":"https:\/\/learn-java-by-example.com\/java\/add-checkbox-items-jlist\/","title":{"rendered":"How do add a checkbox to items in a JList?"},"content":{"rendered":"

We often get asked about how to implement a list of checkboxes using Swing. Using a JList filled with JCheckbox’s seems the obvious solution, however JList does not support cell editors so this does not work. <\/p>\n

One possible solutions is to use a single column JTable and store boolean’s as the cell value (the default editor used by a JTable for booleans is a JCheckbox). (Let us know if you would like to see an example)<\/p>\n

The other solution is to use a JList with a few customisations to make it work as required. We basically need to add 3 things:<\/p>\n

    \n
  1. Use a JCheckbox as the list cell renderer<\/li>\n
  2. Use a MouseListener to change the state of the list item when clicked<\/li>\n
  3. Ensure you list items have a property that indicates whether they are selected<\/li>\n<\/ol>\n
    \r\npackage com.learnjava.swing;\r\n\r\nimport java.awt.Component;\r\nimport java.awt.event.MouseAdapter;\r\nimport java.awt.event.MouseEvent;\r\n\r\nimport javax.swing.JCheckBox;\r\nimport javax.swing.JFrame;\r\nimport javax.swing.JList;\r\nimport javax.swing.JScrollPane;\r\nimport javax.swing.ListCellRenderer;\r\nimport javax.swing.ListSelectionModel;\r\n\r\npublic class CheckboxList {\r\n\r\n\tpublic static void main(String args[]) {\r\n\t\tJFrame frame = new JFrame();\r\n\t\tframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\r\n\r\n\t\t\/\/ Create a list containing CheckboxListItem's\r\n\r\n\t\tJList<CheckboxListItem> list = new JList<CheckboxListItem>(\r\n\t\t\t\tnew CheckboxListItem[] { new CheckboxListItem("apple"),\r\n\t\t\t\t\t\tnew CheckboxListItem("orange"),\r\n\t\t\t\t\t\tnew CheckboxListItem("mango"),\r\n\t\t\t\t\t\tnew CheckboxListItem("paw paw"),\r\n\t\t\t\t\t\tnew CheckboxListItem("banana") });\r\n\r\n\t\t\/\/ Use a CheckboxListRenderer (see below)\r\n\t\t\/\/ to renderer list cells\r\n\r\n\t\tlist.setCellRenderer(new CheckboxListRenderer());\r\n\t\tlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\r\n\r\n\t\t\/\/ Add a mouse listener to handle changing selection\r\n\r\n\t\tlist.addMouseListener(new MouseAdapter() {\r\n\t\t\tpublic void mouseClicked(MouseEvent event) {\r\n\t\t\t\tJList<CheckboxListItem> list =\r\n\t\t\t\t\t(JList<CheckboxListItem>) event.getSource();\r\n\r\n\t\t\t\t\/\/ Get index of item clicked\r\n\r\n\t\t\t\tint index = list.locationToIndex(event.getPoint());\r\n\t\t\t\tCheckboxListItem item = (CheckboxListItem) list.getModel()\r\n\t\t\t\t\t\t.getElementAt(index);\r\n\r\n\t\t\t\t\/\/ Toggle selected state\r\n\r\n\t\t\t\titem.setSelected(!item.isSelected());\r\n\r\n\t\t\t\t\/\/ Repaint cell\r\n\r\n\t\t\t\tlist.repaint(list.getCellBounds(index, index));\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\tframe.getContentPane().add(new JScrollPane(list));\r\n\t\tframe.pack();\r\n\t\tframe.setVisible(true);\r\n\t}\r\n}\r\n\r\n\/\/ Represents items in the list that can be selected\r\n\r\nclass CheckboxListItem {\r\n\tprivate String label;\r\n\tprivate boolean isSelected = false;\r\n\r\n\tpublic CheckboxListItem(String label) {\r\n\t\tthis.label = label;\r\n\t}\r\n\r\n\tpublic boolean isSelected() {\r\n\t\treturn isSelected;\r\n\t}\r\n\r\n\tpublic void setSelected(boolean isSelected) {\r\n\t\tthis.isSelected = isSelected;\r\n\t}\r\n\r\n\tpublic String toString() {\r\n\t\treturn label;\r\n\t}\r\n}\r\n\r\n\/\/ Handles rendering cells in the list using a check box\r\n\r\nclass CheckboxListRenderer extends JCheckBox implements\r\n\t\tListCellRenderer<CheckboxListItem> {\r\n\r\n\t@Override\r\n\tpublic Component getListCellRendererComponent(\r\n\t\t\tJList<? extends CheckboxListItem> list, CheckboxListItem value,\r\n\t\t\tint index, boolean isSelected, boolean cellHasFocus) {\r\n\t\tsetEnabled(list.isEnabled());\r\n\t\tsetSelected(value.isSelected());\r\n\t\tsetFont(list.getFont());\r\n\t\tsetBackground(list.getBackground());\r\n\t\tsetForeground(list.getForeground());\r\n\t\tsetText(value.toString());\r\n\t\treturn this;\r\n\t}\r\n}\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"

    We often get asked about how to implement a list of checkboxes using Swing. Using a JList filled with JCheckbox’s seems the obvious solution, however JList does not support cell editors so this does not work. One possible solutions is to use a single column JTable and store boolean’s as the cell value (the default…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true,"jetpack_social_options":[]},"categories":[4,15,89],"tags":[72,75,71,74,73,70],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p6Yyl2-43","jetpack-related-posts":[{"id":300,"url":"https:\/\/learn-java-by-example.com\/java\/control-decimal-places-displayed-jtable-column\/","url_meta":{"origin":251,"position":0},"title":"How to control decimal places displayed in JTable column?","date":"September 10, 2015","format":false,"excerpt":"Rendering of table cells is handled by instances of TableCellRenderer. By default JTable uses a DefaultTableCellRenderer to render all of its cells. To control the number of decimal places used we just need to subclass DefaultTableCellRenderer and format the cell double value before passing the (formatted) value to to the\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":98,"url":"https:\/\/learn-java-by-example.com\/java\/calculator-keypad\/","url_meta":{"origin":251,"position":1},"title":"Calculator Keypad","date":"August 14, 2010","format":false,"excerpt":"This problem involves understanding some of the basics of building a Swing application including how individual components are laid out inside a window, and how your application can react to the user interacting with the application. In this case we need to update a text field whenever a button is\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":214,"url":"https:\/\/learn-java-by-example.com\/java\/convert-inches-centimetres\/","url_meta":{"origin":251,"position":2},"title":"Convert Inches to Centimetres","date":"October 14, 2011","format":false,"excerpt":"The next example was kindly shared by one of our members. She had a Java Swing assignment to create a Swing GUI for converting Inches to Centimetres and had no idea where to start. We helped her break down the problem and come up with a solution. The resulting code\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":308,"url":"https:\/\/learn-java-by-example.com\/java\/jscrollpane-display-scroll-bars\/","url_meta":{"origin":251,"position":3},"title":"How do I get a JScrollPane to always display scroll bars?","date":"November 6, 2015","format":false,"excerpt":"You can achieve this by setting the scroll bar policy on both the verical and horizontal scroll bars.","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":160,"url":"https:\/\/learn-java-by-example.com\/java\/pascals-triangle\/","url_meta":{"origin":251,"position":4},"title":"Pascals Triangle","date":"February 13, 2011","format":false,"excerpt":"Write a Java application that prints the first 10 lines of Pascals Triangle. Each row of a Pascals Triangle can be calculated from the previous row so the core of the solution is a method that calculates a row based on the previous row which is passed as input. Once\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":154,"url":"https:\/\/learn-java-by-example.com\/java\/prime-numbers\/","url_meta":{"origin":251,"position":5},"title":"Prime numbers","date":"January 21, 2011","format":false,"excerpt":"The assignment here is to calculate all prime numbers less than 100. The solution provided uses the following to determine if a given number is prime. 2 is prime Any number divisible by 2 is not prime If the number is divisible by any odd number then it is not\u2026","rel":"","context":"In "Java"","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts\/251"}],"collection":[{"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/comments?post=251"}],"version-history":[{"count":1,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts\/251\/revisions"}],"predecessor-version":[{"id":252,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/posts\/251\/revisions\/252"}],"wp:attachment":[{"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/media?parent=251"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/categories?post=251"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learn-java-by-example.com\/wp-json\/wp\/v2\/tags?post=251"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}