Add action to a JButton created by another JButton

前端 未结 3 1404
忘了有多久
忘了有多久 2021-01-24 10:39

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?

For example:

3条回答
  •  粉色の甜心
    2021-01-24 11:27

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

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

提交回复
热议问题