Java 将操作添加到由另一个JButton创建的JButton

Java 将操作添加到由另一个JButton创建的JButton,java,swing,jbutton,actionlistener,Java,Swing,Jbutton,Actionlistener,我有一个Jbutton,按下它会创建另一个按钮,新按钮会添加到面板中。如何将actionListener添加到新按钮 例如: JButton button = new JButton("lala"); button.addActionListener(this); public void actionPerformed(ActionEvent event) { if (event.getSource() == button) {

我有一个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);
        }
       }
我想给新按钮添加操作,我该怎么做

编辑的代码:

 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");
    }
  }

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

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

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");
      }
    }

这将创建监听器的实例,并在单击按钮时将其添加到按钮中。一种方法是使用包含监听器的内部类:

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");
      }
    }

这将创建监听器的实例,并在单击按钮时将其添加到按钮中。
newButton
实例需要填写其
actionPerformed
方法。我看到按钮中添加了一个
ActionListener
,但这仅仅意味着有人正在列出操作。上面显示的代码没有在
newButton
上定义任何操作,因此没有触发任何事件,
ActionListener
从未收到任何通知。
newButton
实例需要填写其
actionPerformed
方法。我看到按钮中添加了一个
ActionListener
,但这仅仅意味着有人正在列出操作。上面显示的代码没有在
newButton
上定义任何操作,因此不会触发任何事件,
ActionListener
从未收到任何通知。

对于每个按钮,您可以创建自己的
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);
    }
}

对于每个按钮,您可以创建自己的
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);
    }
}

但是我应该把内部类放在哪里呢?它是否出自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:addActionListenerjavax.swing.AbstractButton中的(java.awt.event.ActionListener)不能应用于(EUCountriesGUI.alitener)试着用一些代码编辑你的帖子,或者发布一个新的问题,我可以看一看itOk,我一行一行地浏览了你发布的代码。据我所知,一切似乎都很好。不要认为这是一个问题,但是测试一下,创建一个对你用按钮添加到数组中的按钮的引用。E.I JButton button=new JButton(name,flag);newButton[click-1]=button;因此,请确保listener类在构造函数外部和任何方法外部声明。此外,我对listener类进行了一些编辑,如果您将listener添加到多个按钮中,则该类会起作用,因此请检查我的帖子。但是,我将内部类放在哪里?它是否在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.alitener)试着用一些代码编辑你的帖子,或者发布一个新的问题,我可以看一看itOk,我一行一行地浏览了你发布的代码。据我所知,一切似乎都很好。不要认为这是一个问题,但是测试一下,创建一个对你用按钮添加到数组中的按钮的引用。E.I JButton button=new JButton(name,flag);newButton[点击-1]=button;此外,请确保侦听器类在构造函数外部和任何方法外部声明。此外,我对侦听器类进行了一些编辑,如果您将侦听器添加到多个按钮,则该类将起作用。因此,请检查我的postNo,您的
alitener
类必须实现
ActionListnere
,因为您正在执行此操作
addActionListener(…)
或者您编写
newButton[单击-1]。addMouseListener(新的Alitener())
使其工作。啊,确实如此。您正在调用addActionListener,但按钮上需要aListener类的应该是addMouseListener,或者您可以让该类实现ActionListener,而不是扩展MouseAdapter,但是您需要将该方法更改为public void actionPerformed(ActionEvent e)与其用鼠标单击来更快地获得更好的帮助,不如发布一个。但简而言之:1)应用程序资源通常只能通过URL访问,而接受
字符串的
ImageICon
构造函数将其解释为
文件
路径。2)此GUI的整个逻辑似乎是可疑的。它的目的是什么?3)布局更可能遵循组件的首选大小,即n大小。但是设置首选大小时要非常小心,这不是一件容易的事。4)在按钮中添加
ActionListener
而不是
MouseListener
。不,您的
Alitener
类必须实现
ActionListener
,因为您正在执行
addActionListener(…)
或编写
新按钮[单击-1].addMouseListener(新的Alitener())
使其工作。啊,确实如此。您正在调用addActionListener,但按钮上需要aListener类的应该是addMouseListener,或者您可以让该类实现ActionListener,而不是扩展MouseAdapter,但是您需要将该方法更改为public void actionPerformed(