我有一个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++;
}
}
答案 0 :(得分:1)
如果我理解正确,您可以设置单选按钮的名称:
self.path = (CGMutablePathRef)CFAutorelease(CGPathCreateMutable());
并在a[x]=new JRadioButton(rs.getString("name"));
a[x].setName(rs.getString("name"));
中获得了操作的来源:
ActionPerformed
答案 1 :(得分:0)
为每个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
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);
}
}
有关详细信息,请参阅How to Use Buttons, Check Boxes, and Radio Buttons
使用a[x] = new JRadioButton(new MessageAction(rs.getString("name"), "Hello from " + x);
API在自包含的工作单元中包围消息和操作...
{{1}}
然后将其应用于您的按钮...
{{1}}
有关详细信息,请参阅How to Use Actions。