【问题标题】:Add action to a JButton created by another JButton向另一个 JButton 创建的 JButton 添加操作
【发布时间】:2012-03-22 14:29:29
【问题描述】:

我有一个 Jbutton,当按下它时会创建另一个按钮并将新按钮添加到面板中。如何将 actionListener 添加到新按钮?

例如:

JButton button = new JButton("lala");
button.addActionListener(this);

    public void actionPerformed(ActionEvent event)
      {
        if (event.getSource() == button)
        {
          JButton newButton = new JButton("ahah");
          newButton.addActionListener(this);
        }
       }

我想给 newButton 添加动作,我该怎么做?

编辑代码:

 public void actionPerformed(ActionEvent event)
  {
  if (event.getSource() == button)
    {
      String name = tfOne.getText();
      Icon flag = new ImageIcon("flag/"+name+".png");
      JButton[] newButton = new JButton[click]; 
      newButton[click-1] = new JButton(name, flag);
      p2.add(newButton[click-1]);
      newButton[click-1].addActionListener(new aListener());
      p2.setLayout(new GridLayout(5+click,1)); //p2 is a panel that has been created
      setSize(500,450+(click*20));

      click++; //number of times the button is pressed
    }
  }

  public class aListener extends MouseAdapter
  { 
    public void mouseClicked(MouseEvent e)
    {
      tfOne.setText("lala");
    }
  }

代码组织得不好,但这或多或少是我想做的

【问题讨论】:

  • 不,您的aListener 类必须实现ActionListnere,因为您正在执行addActionListener(...)或者您编写newButton[click - 1].addMouseListener(new aListener()); 以使其工作。
  • 确实如此。您正在调用 addActionListener,但它应该是需要 aListener 类的按钮上的 addMouseListener,或者您可以让该类实现 ActionListener 而不是扩展 MouseAdapter,但是您需要将方法更改为 public void actionPerformed(ActionEvent e)鼠标点击次数
  • 如需尽快获得更好的帮助,请发帖 SSCCE。但简而言之:1) 应用程序资源通常只能通过 URL 访问,而接受 StringImageICon 构造函数将其解释为 File 路径。 2) 看来这个 GUI 的整个逻辑是可疑的。它的目的是什么? 3) 布局更可能尊重组件的首选尺寸,而不是尺寸。但是设置首选尺寸时要格外小心,这不是轻而易举的事情。 4) 向按钮添加ActionListener 而不是MouseListener

标签: java swing jbutton actionlistener


【解决方案1】:

一种方法是让内部类包含侦听器:

public void actionPerformed(ActionEvent event)
  {
    if (event.getSource() == button)
    {
      JButton newButton = new JButton("ahah");
      newButton.addMouseListener(new yourListener());
    }
   }  

//add this class as a inner class
   public class aListener extends MouseAdapter
   { 
      public void mouseClicked(MouseEvent e)
      {
         JButton buttonReference=(JButton)e.getSource(); // you want this since hardcoding the name of the button is bad if you want listeners for more then one button
         buttonReference.setText("lala");
      }
    }

这将创建一个 yourListener 的实例,并在您单击它时将其添加到按钮

【讨论】:

  • 但是我在哪里放置内部类?是否超出了 actionPerformed() 方法?
  • 是的,你把它放在 actionPreformed 之外,就像你通常对内部类所做的那样。我通常把我内心的听众放在我班的最后(毕竟方法)
  • 我可能做错了什么,它给了我一个错误:发现 1 个错误:文件:C:\Users\Gonçalo\Desktop\MAIN PROJECTS\File Project\EUCountriesGUI.java [行:139 ] 错误:C:\Users\Gonçalo\Desktop\MAIN PROJECTS\File Project\EUCountriesGUI.java:139:javax.swing.AbstractButton 中的 addActionListener(java.awt.event.ActionListener) 无法应用于 (EUCountriesGUI.aListener)
  • 尝试用一些代码编辑你的帖子,或者发布一个新问题,我可以看看它
  • 好的,我逐行查看了您发布的代码。据我所知,一切似乎都很好。不要认为这是一个问题,但测试以创建对您使用按钮添加到数组中的按钮的引用。 E.i JButton button = new JButton(name, flag); newButton[click-1]=按钮;除此之外,确保侦听器类是在构造函数之外声明的,并且在任何方法之外。此外,如果您将侦听器添加到一个以上的按钮,我还对侦听器类进行了一些编辑,因此请查看我的帖子
【解决方案2】:

您可以为每个按钮创建自己的actionPerformed(...) 方法,如下例所述: 你的意思是这样做吗:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonAction
{
    private JPanel contentPane;
    private JButton updateButton;
    private int count = 0;
    private ActionListener updateListener = new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            final JButton button = new JButton("" +  count); 
            button.setActionCommand("" + count);
            button.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent event)
                {
                    System.out.println("My COMMAND is : " + event.getActionCommand());
                }
            });
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    contentPane.add(button);
                    contentPane.revalidate();
                    contentPane.repaint();
                }
            });
            count++;
        }
    };

    private void createAndDisplayGUI()
    {
        JFrame frame = new JFrame("BUTTON ACTIONS");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);

        contentPane = new JPanel();
        contentPane.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));

        updateButton = new JButton("UPDATE GUI");
        updateButton.addActionListener(updateListener);

        frame.add(contentPane, BorderLayout.CENTER);
        frame.add(updateButton, BorderLayout.PAGE_END);

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        Runnable runnable = new Runnable()
        {
            public void run()
            {
                new ButtonAction().createAndDisplayGUI();
            }
        };
        SwingUtilities.invokeLater(runnable);
    }
}

【讨论】:

    【解决方案3】:

    newButton 实例需要填写其actionPerformed 方法。我看到您在按钮中添加了ActionListener,但这仅表示有人正在列出操作。您在上面显示的代码没有在 newButton 上定义任何操作,因此不会触发任何事件,ActionListener 永远不会收到任何通知。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-06
      • 2013-12-13
      • 1970-01-01
      • 2013-10-06
      • 2013-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多