有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JRadioButton名称的名称空间Java操作侦听器

如何将ActionListener添加到元素的名称中

我有一个为我创建表的循环

enter image description here

在这个循环中,我创建了单选按钮:

ZFbutton = new JRadioButton();
ZFbutton.setName(""+key);       

。。其中key来自循环

目前,我尝试通过以下方式访问JRadioButtons:

 ZFbutton.addActionListener (new ActionListener () {
    public void actionPerformed(ActionEvent e) {
      try {
         if(ZFbutton.isSelected() == true){

但这只允许我访问最后创建的JRadioButton,这从逻辑角度讲是有意义的。所以我给每个单选按钮一个唯一的名称:ZFbutton.setName(""+key);,但是我如何用元素的名称创建ActionListener呢


共 (2) 个答案

  1. # 1 楼答案

    将所有按钮添加到一个数组中,并通过该数组访问每个按钮。这是一个简单的方法,但是@StimpsonCat提到的方法也应该有效

    JRadioButoon[] buttons=new JRadioButton[x];
    buttons[0]=new JRadioButton();
    ...
    
  2. # 2 楼答案

    您可以将actionListener添加到每个按钮。您可以为按钮设置ActionCommand,而不是设置按钮的名称

    button.setActionCommand("Alpha");
    

    然后,您可以像这样识别按下了哪个按钮:

    public void actionPerformed(ActionEvent ae) {
    String ac = ae.getActionCommand();
    
    if (ac.equals("Alpha")) {
      if (jbtnB.isEnabled()) {
        System.out.println("Alpha pressed. Beta is disabled.");
        jbtnB.setEnabled(false);
      } else {
        System.out.println("Alpha pressed. Beta is enabled.");
        jbtnB.setEnabled(true);
      }
    } else if (ac.equals("Beta"))
      System.out.println("Beta pressed.");
    }
    

    您可以从actionEvent获取actionCommand