Add action to a JButton created by another JButton

前端 未结 3 1403
忘了有多久
忘了有多久 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:24

    For each button you can create it's own actionPerformed(...) method, as described in the example below : Do you mean to do this :

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

提交回复
热议问题