Results 1 to 15 of 15
  1. #1
    heba.farouk is offline Member
    Join Date
    Aug 2008
    Posts
    3
    Rep Power
    0

    Default ComboBox with CheckBoxes

    Hi all

    I would like to have a combobox that its items are checkboxes, like the example attached.

    can u help me

    Thanks in advance
    Attached Thumbnails Attached Thumbnails ComboBox with CheckBoxes-dropdown.jpg  

  2. #2
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    For each item of the Combo box, try to set the model as a check box. I've never try it, but it should work. Have a try and see.

  3. #3
    heba.farouk is offline Member
    Join Date
    Aug 2008
    Posts
    3
    Rep Power
    0

    Default

    I tired this, and it's not working, the combobox data is :
    Java Code:
    javax.swing.JCheckBox[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@14b03ea,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=2,bottom=2,right=2],paintBorder=false,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=One]
    the model only sees the check box as a string

    Here is my code (May be i missed something )

    Java Code:
    .
    .
    .
    .
    //setting the comboBox model
    JCheckBox[] featuresList = new JCheckBox[2];
    		featuresList[0] = new JCheckBox("One");
    		featuresList[1] = new JCheckBox("two");
    		ComboBoxDataModel model = new ComboBoxDataModel(featuresList);
    		featuresComboBox.setModel(model);
    
    .
    .
    .
    
    //The data model class
    import java.awt.CheckboxGroup;
    
    import javax.swing.AbstractListModel;
    import javax.swing.ComboBoxModel;
    import javax.swing.JCheckBox;
    import javax.swing.event.ListDataListener;
    
    public class ComboBoxDataModel extends AbstractListModel implements ComboBoxModel{
    
    	JCheckBox[] choices;
    	Object selectedItem;
    	
    	public ComboBoxDataModel(JCheckBox[] choices){
    		this.choices = choices;
    	}
    	@Override
    	public Object getSelectedItem() {
    		return this.selectedItem;
    	}
    
    	@Override
    	public void setSelectedItem(Object anItem) {
    		this.selectedItem = anItem;
    	}
    
    	@Override
    	public Object getElementAt(int index) {
    		return (JCheckBox)choices[index];
    	}
    
    	@Override
    	public int getSize() {
    		return choices.length;
    	}
    }
    Thanks

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Eranga View Post
    For each item of the Combo box, try to set the model as a check box. I've never try it, but it should work. Have a try and see.
    I don't see how that would work because the standard JComboBox only displays the results from a call to the object's toString() method. I suppose you have to alter the renderer that the combobox uses to display the items. Have a look at this link here.

  5. #5
    Niveditha's Avatar
    Niveditha is offline Senior Member
    Join Date
    May 2008
    Posts
    307
    Rep Power
    7

    Default

    Yes even i agree with Fuberable.
    ComboBox will select only one item at the time and checkBoxes are used when user is allowed to select multiple items which contradicts the use of ComboBox.

    I think the initiator needs to rethink about the use of checkbox in comboBox.
    To finish sooner, take your own time....
    Nivedithaaaa

  6. #6
    heba.farouk is offline Member
    Join Date
    Aug 2008
    Posts
    3
    Rep Power
    0

    Default

    yes, Fubarable, i made my renderer, my problem now is that i can't select or deselect the check boxes in the combobox, any solutions !!

    too, i'll have a look on the link u sent, thanks

    here is the code
    Java Code:
    public class CheckListCellRenderer implements ListCellRenderer	{
    	
    	public Component getListCellRendererComponent(JList list, Object value,
    			int index, boolean isSelected, boolean cellHasFocus) {
    		
    		if(index ==-1)
    			return new JLabel("Select features!");
    		JCheckBox checkBox = (JCheckBox)value;
    		checkBox.setUI((BasicCheckBoxUI) MyCheckBoxUI.createUI(checkBox));
    		checkBox.setPreferredSize(new Dimension(214, 25));
    		checkBox.setEnabled(true);
    		return checkBox;
    	}
    	static class MyCheckBoxUI extends BasicCheckBoxUI {
    	    public static ComponentUI createUI(JComponent c) {
    	      return new MyCheckBoxUI();
    	    }
    	  }
    }

  7. #7
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    problem now is that i can't select or deselect the check boxes in the combobox, any solutions !!
    One difficulty with a JComboBox is that the editing takes place in the component and not in the JPopupMenu below it.
    You might try making a custom component for this.
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.Path2D;
    import javax.swing.*;
    
    public class CheckCombo implements ActionListener {
        JPopupMenu popupMenu;
    
        public void actionPerformed(ActionEvent e) {
            JButton button = (JButton)e.getSource();
            Component parent = button.getParent();
            if(popupMenu.getInvoker() == null) {
                popupMenu.setInvoker(parent);
                int w = ((JComponent)parent).getPreferredSize().width;
                Dimension d = popupMenu.getComponent(0).getPreferredSize();
                d.width = w;
                popupMenu.setPopupSize(d);
            }
            Rectangle r = parent.getBounds();
            Point p = r.getLocation();
            Container topLevel = button.getTopLevelAncestor();
            Container cp = ((JFrame)topLevel).getContentPane();
            SwingUtilities.convertPointToScreen(p, cp);
            popupMenu.setLocation(p.x, p.y+r.height);
            popupMenu.setVisible(true);
        }
    
        private JPanel getContent() {
            createPopupMenu();
            JLabel label = new JLabel(" Select Features!");
            label.setBorder(
                BorderFactory.createLineBorder(new Color(175,175,200), 1));
            JButton button = new JButton() {
                protected void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    Graphics2D g2 = (Graphics2D)g;
                    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                        RenderingHints.VALUE_ANTIALIAS_ON);
                    int w = getWidth();
                    double width = 10.0;
                    double x = (w - width)/2.0;
                    double height = 5.0;
                    double y = (getHeight() - height)/2.0;
                    Path2D.Double path = new Path2D.Double();
                    path.moveTo(x, y);
                    path.lineTo(x+width, y);
                    path.lineTo(w/2.0, y+height);
                    path.closePath();
                    g2.fill(path);
                }
    
                public Dimension getPreferredSize() {
                    return new Dimension(20,25);
                }
            };
            button.addActionListener(this);
            JPanel p = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.fill = gbc.BOTH;
            p.add(label, gbc);
            gbc.weightx = 0;
            p.add(button, gbc);
            JPanel panel = new JPanel(new GridBagLayout());
            panel.add(p, gbc);
            Dimension d = p.getPreferredSize();
            d.width = 120;
            p.setPreferredSize(d);
            return panel;
        }
    
        private void createPopupMenu() {
            final CheckComboStore[] stores = {
                new CheckComboStore("one",   true),
                new CheckComboStore("two",   false),
                new CheckComboStore("three", false)
            };
            ActionListener al = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JCheckBox cb = (JCheckBox)e.getSource();
                    String ac = cb.getActionCommand();
                    for(int i = 0; i < stores.length; i++) {
                        if(stores[i].toString().equals(ac)) {
                            stores[i].state = cb.isSelected();
                        }
                    }
                    popupMenu.setVisible(false);
                }
            };
            popupMenu = new JPopupMenu();
            JPanel panel = new JPanel(new GridLayout(0,1));
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            for(int i = 0; i < stores.length; i++) {
                JCheckBox cb = new JCheckBox();
                cb.setActionCommand(stores[i].toString());
                cb.addActionListener(al);
                JLabel label = new JLabel(stores[i].toString(), JLabel.CENTER);
                JPanel p = new JPanel(gridbag);
                gbc.weightx = 0;
                gbc.gridwidth = GridBagConstraints.RELATIVE;
                p.add(cb, gbc);
                gbc.weightx = 1.0;
                gbc.fill = GridBagConstraints.BOTH;
                gbc.gridwidth = GridBagConstraints.REMAINDER;
                p.add(label, gbc);
                panel.add(p);
            }
            popupMenu.add(panel);
        }
    
        private JPanel getComparisonCombo() {
            JComboBox combo = new JComboBox(new String[]{"Select Features!"});
            Dimension d = combo.getPreferredSize();
            System.out.printf("comparisonSize = [%d, %d]%n", d.width, d.height);
            JPanel panel = new JPanel();
            panel.add(combo);
            return panel;
        }
    
        public static void main(String[] args) {
            CheckCombo test = new CheckCombo();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test.getContent());
            f.add(test.getComparisonCombo(), "Last");
            f.setSize(300,200);
            f.setLocation(200,200);
            f.setVisible(true);
        }
    }
    
    class CheckComboStore {
        String text;
        boolean state;
    
        public CheckComboStore(String text, boolean state) {
            this.text = text;
            this.state = state;
        }
    
        public String toString() {
            return text;
        }
    }

  8. #8
    yirenjun is offline Member
    Join Date
    Apr 2009
    Posts
    1
    Rep Power
    0

    Default

    Quote Originally Posted by hardwired View Post
    problem now is that i can't select or deselect the check boxes in the combobox, any solutions !!
    One difficulty with a JComboBox is that the editing takes place in the component and not in the JPopupMenu below it.
    You might try making a custom component for this.
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.Path2D;
    import javax.swing.*;
    
    public class CheckCombo implements ActionListener {
        JPopupMenu popupMenu;
    
        public void actionPerformed(ActionEvent e) {
            JButton button = (JButton)e.getSource();
            Component parent = button.getParent();
            if(popupMenu.getInvoker() == null) {
                popupMenu.setInvoker(parent);
                int w = ((JComponent)parent).getPreferredSize().width;
                Dimension d = popupMenu.getComponent(0).getPreferredSize();
                d.width = w;
                popupMenu.setPopupSize(d);
            }
            Rectangle r = parent.getBounds();
            Point p = r.getLocation();
            Container topLevel = button.getTopLevelAncestor();
            Container cp = ((JFrame)topLevel).getContentPane();
            SwingUtilities.convertPointToScreen(p, cp);
            popupMenu.setLocation(p.x, p.y+r.height);
            popupMenu.setVisible(true);
        }
    
        private JPanel getContent() {
            createPopupMenu();
            JLabel label = new JLabel(" Select Features!");
            label.setBorder(
                BorderFactory.createLineBorder(new Color(175,175,200), 1));
            JButton button = new JButton() {
                protected void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    Graphics2D g2 = (Graphics2D)g;
                    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                        RenderingHints.VALUE_ANTIALIAS_ON);
                    int w = getWidth();
                    double width = 10.0;
                    double x = (w - width)/2.0;
                    double height = 5.0;
                    double y = (getHeight() - height)/2.0;
                    Path2D.Double path = new Path2D.Double();
                    path.moveTo(x, y);
                    path.lineTo(x+width, y);
                    path.lineTo(w/2.0, y+height);
                    path.closePath();
                    g2.fill(path);
                }
    
                public Dimension getPreferredSize() {
                    return new Dimension(20,25);
                }
            };
            button.addActionListener(this);
            JPanel p = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.fill = gbc.BOTH;
            p.add(label, gbc);
            gbc.weightx = 0;
            p.add(button, gbc);
            JPanel panel = new JPanel(new GridBagLayout());
            panel.add(p, gbc);
            Dimension d = p.getPreferredSize();
            d.width = 120;
            p.setPreferredSize(d);
            return panel;
        }
    
        private void createPopupMenu() {
            final CheckComboStore[] stores = {
                new CheckComboStore("one",   true),
                new CheckComboStore("two",   false),
                new CheckComboStore("three", false)
            };
            ActionListener al = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JCheckBox cb = (JCheckBox)e.getSource();
                    String ac = cb.getActionCommand();
                    for(int i = 0; i < stores.length; i++) {
                        if(stores[i].toString().equals(ac)) {
                            stores[i].state = cb.isSelected();
                        }
                    }
                    popupMenu.setVisible(false);
                }
            };
            popupMenu = new JPopupMenu();
            JPanel panel = new JPanel(new GridLayout(0,1));
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            for(int i = 0; i < stores.length; i++) {
                JCheckBox cb = new JCheckBox();
                cb.setActionCommand(stores[i].toString());
                cb.addActionListener(al);
                JLabel label = new JLabel(stores[i].toString(), JLabel.CENTER);
                JPanel p = new JPanel(gridbag);
                gbc.weightx = 0;
                gbc.gridwidth = GridBagConstraints.RELATIVE;
                p.add(cb, gbc);
                gbc.weightx = 1.0;
                gbc.fill = GridBagConstraints.BOTH;
                gbc.gridwidth = GridBagConstraints.REMAINDER;
                p.add(label, gbc);
                panel.add(p);
            }
            popupMenu.add(panel);
        }
    
        private JPanel getComparisonCombo() {
            JComboBox combo = new JComboBox(new String[]{"Select Features!"});
            Dimension d = combo.getPreferredSize();
            System.out.printf("comparisonSize = [%d, %d]%n", d.width, d.height);
            JPanel panel = new JPanel();
            panel.add(combo);
            return panel;
        }
    
        public static void main(String[] args) {
            CheckCombo test = new CheckCombo();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test.getContent());
            f.add(test.getComparisonCombo(), "Last");
            f.setSize(300,200);
            f.setLocation(200,200);
            f.setVisible(true);
        }
    }
    
    class CheckComboStore {
        String text;
        boolean state;
    
        public CheckComboStore(String text, boolean state) {
            this.text = text;
            this.state = state;
        }
    
        public String toString() {
            return text;
        }
    }
    .... no !!!

  9. #9
    cadu.andrade is offline Member
    Join Date
    Jun 2010
    Posts
    3
    Rep Power
    0

  10. #10
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

  11. #11
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,184
    Rep Power
    19

    Default

    Quote Originally Posted by Eranga View Post
    This is a very old thread. Our OP may already solved the problem.
    In the context of the advertisement posted by the same member to the Swing forum (which I've just reported) this resurrection of an old dead thread should be considered link spam.

    db

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Darryl.Burke View Post
    In the context of the advertisement posted by the same member to the Swing forum (which I've just reported) this resurrection of an old dead thread should be considered link spam.

    db
    I wonder if it sits in a bit of a gray zone since this library that he's involved in the development of is offered under an open source (LGPL) license, and the rules (in my mind) should be somewhat different for open source vs. for-profit projects.

  13. #13
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    Darryl, you really believe that it's spamming the forum? My concern is that he post a link to a different resource, and one in a related thread and the other one is in the relevant sub-forum. That's the only two post he has post at the min, and that's his limitation. If he post that link any other place, yes I've ban him most probably. What you think.

  14. #14
    cadu.andrade is offline Member
    Join Date
    Jun 2010
    Posts
    3
    Rep Power
    0

    Default

    Hummm... sorry if it was an old post. I just posted because its a new way to resolve the problem. Maybe a better or easier way.

    tks

  15. #15
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    That's because OP didn't mark the thread solved or not. And also interaction for such an old thread may be time wasting. In most of the cases, if OP found the solution never come back. Some are good at it actually.

Similar Threads

  1. combobox
    By chandu.v in forum New To Java
    Replies: 2
    Last Post: 07-02-2008, 08:36 PM
  2. How to use Mnemonic for CheckBoxes
    By Java Tip in forum javax.swing
    Replies: 0
    Last Post: 06-27-2008, 07:45 PM
  3. How to use Swing CheckBoxes
    By Java Tip in forum javax.swing
    Replies: 0
    Last Post: 06-27-2008, 07:44 PM
  4. Adding checkboxes on frame
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-21-2007, 08:40 AM
  5. Problem with checkboxes
    By carl in forum Java Applets
    Replies: 1
    Last Post: 08-06-2007, 08:33 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •