2015-07-22 65 views
0

我有Jradiobuttons.i的陣列想有實現ActionListener的java的匿名類來得到的JComboBox陣列的值,所以當單選按鈕,用戶按下我可以做的東西,但由於這是一個數組我不能給數組索引使用while循環,所以如何確定我正在使用的Jradiobutton。我想獲取該單選按鈕的文本並將其保存在另一個變量中...我該怎麼做?如何使用匿名類

這是迄今爲止我所做的:

if(count!=0) { 
    rs=pst.executeQuery(); 
    JRadioButton a []=new JRadioButton[count];      
    jPanel3.setLayout(new GridLayout()); 
    int x=0; 
    ButtonGroup bg=new ButtonGroup(); 

    while(rs.next()) {  
    a[x]=new JRadioButton(rs.getString("name")); 
    bg.add(a[x]); 
    jPanel3.add(a[x]); 
    a[x].setVisible(true); 

    a[x].addActionListener(new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent e) {  

      JOptionPane.showMessageDialog(null,a[x].getText()); //here i cant use this x...even though i make x global value of x always will be 6 becouse of while loop. 

     } 
    });     
    x++; 
    }        
}  

回答

1

如果我理解正確的話,你可以設置單選按鈕的名稱:

a[x]=new JRadioButton(rs.getString("name")); 
a[x].setName(rs.getString("name")); 

ActionPerformed你得到的源動作:

public void actionPerformed(ActionEvent e) { 

if(e.getSource() instanceof JRadioButton){ 

    String selectedRadioName = ((JRadioButton) e.getSource()).getName(); 

    JOptionPane.showMessageDialog(null, selectedRadioName); 

} 
+0

thnxxxx這是工作 – pavithra

+0

也可以告訴我什麼是JRadioButton的這個instanceof意味着 – pavithra

+0

由於你的ActionListener實現爲anonymius類,所以你不需要它。如果您點擊了JRadioButton(即動作來源是單選按鈕),那麼您需要檢查/確認和處理,以便在類型轉換時不應該得到類轉換異常。 – Garry

0

你可以...

供應各JRadioButtonActionCommand將通過ActionEvent

a[x]=new JRadioButton(rs.getString("name")); 
a[x].setActionCommand(String.valueOf(x)); 
//... 
a[x].addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 

      String cmd = e.getActionCommand(); 
      int value = Integer.parseInt(cmd); 

      JOptionPane.showMessageDialog(null, a[value].getText()); 
     } 
}); 

可以提供更多細節

你可以看到How to Use Buttons, Check Boxes, and Radio Buttons ...

使用Action API包圍的消息,在工作的獨立裝置動作......

public class MessageAction extends AbstractAction { 

    private String message; 

    public MessageAction(String text, String message) { 
     this.message = message; 
     putValue(NAME, text); 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     JOptionPane.showMessageDialog(null, message); 
    } 

} 

然後將它應用到您的按鈕類似...

a[x] = new JRadioButton(new MessageAction(rs.getString("name"), "Hello from " + x); 

詳情請參閱How to Use Actions