2013-03-24 64 views
0

我没有分组我的jradiobuttons,以便用户可以选择多个选择,我可以存储在节点阵列..但它只能读取一次。代码有什么问题?请赐教为什么我的jradiobutton只能使用一次?

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

如果您的目标是允许用户选择多个项目,请使用JCheckBox而不是JRadioButton。视觉线索很重要。大多数人会认为只能选择一个单选按钮。你不想让用户猜测事物是如何工作的,就像你不会把推杆放在向内开放的门上一样。 – VGR 2013-03-24 12:48:39

回答

2

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

UPDATE

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对象创建并添加到JPanel。您应该在循环中创建每个JRadioButton以在for循环中注册ActionListener。这会使ActionEventJRadioButton触发,您将添加到JPanel

+0

感谢您的帮助,但它仍然是一样的..它只存储我做的第一选择。 – user2064467 2013-03-24 11:23:44

+0

@ user2064467看我的更新。 – 2013-03-24 12:53:43

相关问题