[英]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.