2017-04-04 51 views
1

我有一些單選按鈕,我把它放在單選按鈕組中。 那麼,當我點擊一個特定的單選按鈕時,如何獲得單選按鈕索引值或選定的索引值。如何從代號爲1的單選按鈕組中獲取當前單選按鈕索引值?

這裏是我的代碼

bg=new ButtonGroup(); 
for(i=0;i<8;i++){ 
rbt =new RadioButton(); 
rbt.setName("rbt"+i); 
radioList.add(rbt); 
} 
for(int i=0;i<radioList.size();i++){ 
    radioList.get(i).addPointerPressedListener(new ActionListener() { 
         @Override 
         public void actionPerformed(ActionEvent evt) { 
          for(int i=0;i<radioList.size();i++){ 
            Log.p("================"+bg.getSelectedIndex); 
          } 
         } 
        }); 
} 

在上面的代碼我得到預先選擇的值不是當前。重視提前

回答

1

pointerPressed

感謝的單選按鈕已經處理了事件之前被調用。改爲使用addActionListener,狀態更改後觸發,因此所選索引應爲當前選定的單選按鈕。

+0

謝謝你,史蒂夫·漢納addActionListener方法,對我的作品 –

1

您應該添加在容器中的單選按鈕以及ButtonGroup中並調用ButtonGroup中的getselectedIndex獲取當前指數如下面的代碼

void testRadio(Form form) { 
     Container radioList = new Container(new BoxLayout(BoxLayout.Y_AXIS)); 
     ButtonGroup bg = new ButtonGroup(); 
     for (int i = 0; i < 8; i++) { 
      RadioButton rbt = new RadioButton(); 
      rbt.setName("rbt" + i); 
      rbt.setText("rbt" + i); 
      **radioList.add(rbt); 
      bg.add(rbt);** 
     } 
     bg.setSelected(0); 
     form.add(radioList); 
     Button getIndexButton = new Button("Get Radio Index"); 
     getIndexButton.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent evt) { 
//    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. 
       Log.p("================" + bg.getSelectedIndex()); 
      } 
     }); 
     form.add(getIndexButton); 

    } 
相關問題