为什么我的jradiobutton只服用一次?

时间:2013-03-24 09:46:34

标签: java swing user-interface jradiobutton buttongroup

我没有对我的jradiobuttons进行分组,以便用户可以选择多个选项,我可以存储在节点数组中。但它只能读取一次。代码有什么问题?请赐教我

private String[] showGUIForNodeDeletion() {

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(map.size(), 1));
        ButtonGroup btnGrp = new ButtonGroup();
        final String nodes[] = new String[10];
        Set<String> keySet = map.keySet();

        for (String name : keySet) {

            btnRadio = new JRadioButton(name);
            btnRadio.setActionCommand(map.get(name).x + "," + map.get(name).y + "," + name);
                        //btnGrp.add(btnRadio);
            panel.add(btnRadio);
        }

        btnRadio.addActionListener(new ActionListener() {
            int x = 0;

            public void actionPerformed(ActionEvent e) {

                nodes[x] = ((JRadioButton) e.getSource()).getActionCommand();
                System.out.println("Node counting " + x);
                x++;
            }
        });

        if (keySet.isEmpty()) {
            JOptionPane.showMessageDialog(AnotherGuiSample.this, "Work Space is empty", "Error", JOptionPane.ERROR_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(AnotherGuiSample.this, panel, "Select node to remove", JOptionPane.INFORMATION_MESSAGE);
        }
        for(int x = 0; x < nodes.length; x++ )
        System.out.println("node is " + nodes[x]);

        return nodes;
    }

1 个答案:

答案 0 :(得分:2)

你的for循环代码应该是这样的:

<强>更新

Set<String> rbSet = new TreeSet<String>();
for (String name : keySet) {

    btnRadio = new JRadioButton(name);
    btnRadio.setActionCommand(map.get(name).x + "," + map.get(name).y + "," + name);
    btnRadio.addActionListener( new ActionListener()
    {
        public void actionPerformed(ActionEvent evt)
        {
            JRadioButton obj = (JRadioButton)evt.getSource();
            if (obj.isSelected())
            {
                rbSet.add(obj.getActionCommand());
            }
            else 
            {
                rbSet.remove(obj.getActionCommand());
            }
        }
    });
    panel.add(btnRadio);
}
int counter = 0 ;
for (String action : rbSet )
{
    nodes[counter++] = action;
}

发生了什么,你正在注册ActionListener和for循环中创建的最后一个对象,因为你是在for循环之后完成的。这就是为什么它仅针对创建并添加到JRaioButton的lat JPanel对象进行触发。您应该在for循环中注册ActionListener,并在循环中创建每个JRadioButton。这样,ActionEvent会为您添加到JRadioButton的每个JPanel触发。