将动作添加到由另一个JButton创建的JButton [英] Add action to a JButton created by another JButton

查看:147
本文介绍了将动作添加到由另一个JButton创建的JButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Jbutton that when pressed creates another button and the new button is added to the panel. How to I add an actionListener to the new button?

例如:

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添加动作,怎么做我这样做了吗?

I want to add action to the newButton, how do I do it?

编辑代码:

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

代码组织不好但是或多或少我想做什么

The code is not well organized but that's more or less what I want to do

推荐答案

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

One way would be to have a inner class containg the listener:

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的一个实例,并添加点击它时按钮

This will create a instance of yourListener, and add that to the button when you click it

这篇关于将动作添加到由另一个JButton创建的JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆