0

我没有对我的 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;
    }
4

1 回答 1

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

发生了什么,您正在注册ActionListenerfor 循环中创建的最后一个对象,因为您在 for 循环之后执行了它。这就是为什么它只为JRaioButton创建并添加到JPanel. 您应该ActionListener在 for 循环中注册每个JRadioButton在循环中创建的。这使得ActionEvent每一个JRadioButton你添加到的JPanel.

于 2013-03-24T10:00:46.343 回答