2013-03-24 62 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

相關問題