[英]Disable actionListener for JComboBox (when using anonymous class)
[英]how to get a value from a Jcombobox array using a anonymous class
我有一個Jradiobuttons.i數組,我正在嘗試實現ActionListener的java匿名類,因此當用戶按下單選按鈕時,我可以做些什么,但是由於這是一個數組,因此我無法使用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++;
}
}
如果我理解正確,則可以設置單選按鈕的名稱:
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 );
}
為每個JRadioButton
提供一個ActionCommand
,可通過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());
}
});
有關更多詳細信息,請參見如何使用按鈕,復選框和單選按鈕 。
使用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);
有關更多詳細信息,請參見如何使用動作 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.