Frage

Before I asked this question, I went through many examples, some of them are related, but did not answer my needs:

I have a list as keyMessageList which includes id as Long and associated keyWord as String.

I displayed keyWord's name on my jpanel using following code:

    for (KeyMessage obj : keyMessageList) {
        checkBox = new JCheckBox(obj.getSmsKey());
        displayKeywordPanel.checkBooxPanel.add(checkBox);
    }

I got the following output:

output image

Now, My requirement is: If I select keywords, I need to get the id associated with the selected keyword. I have done similar things many times in web applications like this, but now I need to do the same thing on swing. I used the following code on web application to fulfill the requirements. Code for web:

<h:selectOneMenu id="branch" value="#{createUser.branchId}" required="true" requiredMessage="Please choose branch">
          <f:selectItems value="#{allBranch}"/>
</h:selectOneMenu>

Can any swing expert please help me.

Note I may select multiple checkBox and keyMessageList returns from JPA query.

War es hilfreich?

Lösung

I have a list as keyWordsList which includes id and associated keyWord.

Don't use a List. Instead use a Map with the "keyword" as the key and the "id" as the value. Then when you select a check box you get the ID from the Map.

Another option would be to create you JCheckBox as follows:

JCheckBox checkBox = new JCheckBox(keyword);
checkbox.setActionCommand( id );

Then later you access the id of the selected checkbox by using the getActionCommand() method.

Andere Tipps

You can get displayKeywordPanel.checkBooxPanel.getComponents() array. Iterate through the array and store indexes. Then use the indexes to get elements from the keyMessageList

I think you can extend your own JCheckBox (let say JCheckBoxWithID) which allow you keep the id. Then use a List to store/remove ids everytime a checkbox is selected/unselected using an ItemListener

This way you'll be avoiding iterate over your checkboxPanel asking who is selected and keeping separated responsibilities:

  • JCheckBox just shows a keyword and holds an id
  • List just stores selected ids
  • ItemListener handles the event when a JCheckBox becomes selected/unselected and adds/removes its id to/from List

Hope this example be helpful:

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Tests {

    private void initGUI(){

        /* This list will store selected ids */
        final List<Integer> selectedIds = new ArrayList<>();

        ItemListener itemListener = new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getSource() instanceof JCheckBoxWithID){
                    JCheckBoxWithID checkBoxWithID = (JCheckBoxWithID) e.getSource();
                    if(checkBoxWithID.isSelected()){
                        selectedIds.add(checkBoxWithID.getId());
                    } else {
                        selectedIds.remove(checkBoxWithID.getId());
                    }
                }
            }
        };

        String[] keyWords = new String[]{"Help 1", "Help 2", "Help 3", "Help 4", "Help 5", "Help 6"};
        Integer id = 0;
        JPanel checkBoxesPanel = new JPanel(new GridLayout(3,3));

        /* Add many checkbox as you keywords you have */
        for(String keyWord : keyWords){
            JCheckBoxWithID checkBoxWithID = new JCheckBoxWithID(keyWord, id);
            checkBoxWithID.addItemListener(itemListener);
            checkBoxesPanel.add(checkBoxWithID);
            id++;
        }

        JButton submit = new JButton("Submit");
        submit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, Arrays.toString(selectedIds.toArray()), "Selected IDs", JOptionPane.INFORMATION_MESSAGE);
            }
        });

        JPanel content = new JPanel(new FlowLayout(FlowLayout.LEADING));
        content.add(checkBoxesPanel);
        content.add(submit);

        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

    public static void main(String[] args) {        
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Tests().initGUI();
            }
        });      
    }

    class JCheckBoxWithID extends JCheckBox {
        /* I use Integer but the id could be whatever you want, the concept is the same */
        private Integer _id;

        public JCheckBoxWithID(String text, Integer id) {
            super(text);
            _id = id;
        }

        public void setId(Integer id){
            _id = id;
        }

        public Integer getId(){
            return _id;
        }
    }
}

Here's a print screen:

enter image description here

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top