【问题标题】:Get selected `JCheckBox` associated `id` on swing在摇摆时获取选定的`JCheckBox`关联`id`
【发布时间】:2013-10-04 12:38:39
【问题描述】:

在我问这个问题之前,我浏览了很多例子,其中一些是相关的,但没有回答我的需求:

我有一个 keyMessageList 列表,其中包括 id 作为 Long 和关联 keyWord 作为 String

我使用以下代码在我的 jpanel 上显示了 keyWord 的名字:

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

我得到以下输出:

现在,我的要求是:如果我选择关键字,我需要获得与所选keyword 关联的id。我在web applications 中做过很多次类似的事情,但现在我需要在挥杆时做同样的事情。我在 Web 应用程序上使用了以下代码来满足要求。 网页代码:

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

哪位挥杆专家可以帮帮我。

注意我可以选择多个复选框并从 JPA 查询返回keyMessageList

【问题讨论】:

    标签: java swing jcheckbox


    【解决方案1】:

    我有一个 keyWordsList 列表,其中包括 id 和关联的 keyWord。

    不要使用列表。而是使用Map,其中“关键字”作为键,“id”作为值。然后,当您选中一个复选框时,您会从地图中获取 ID。

    另一种选择是按如下方式创建 JCheckBox:

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

    然后您可以使用 getActionCommand() 方法访问所选复选框的 id。

    【讨论】:

      【解决方案2】:

      你可以得到displayKeywordPanel.checkBooxPanel.getComponents()数组。遍历数组并存储索引。然后使用索引从keyMessageList获取元素

      【讨论】:

        【解决方案3】:

        我认为你可以扩展你自己的JCheckBox(比如说JCheckBoxWithID),这样你就可以保留id。然后每次使用ItemListener 选择/取消选择复选框时,使用List 存储/删除 ids

        这样你就可以避免重复你的checkboxPanel询问谁被选中并保持分离的职责:

        • JCheckBox 只是显示一个关键字并持有一个 id
        • List 只存储选定的 ID
        • ItemListenerJCheckBox 被选中/取消选中时处理事件,并将其 id 添加到 List 或从 List 中删除

        希望这个示例对您有所帮助:

        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;
                }
            }
        }
        

        这是一个打印屏幕:

        【讨论】:

        • 真的吗?扩展JCheckBox 只是为了那个?您已经可以使用putClientProperty 方法在JComponent 上存储额外的值。在这种情况下,扩展的附加值是什么?
        • 为什么不呢?是的,您可以使用putClientProperty,但恕我直言,它不太直观。考虑阅读其他人的代码并尝试弄清楚为什么原始开发人员以这种方式放置/读取属性。我认为,如果您制作自己的自定义类,应该更容易理解它添加的与其超类相关的功能。
        猜你喜欢
        • 1970-01-01
        • 2012-04-20
        • 2014-08-30
        • 1970-01-01
        • 1970-01-01
        • 2013-06-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多