Search code examples
javaswingjbutton

How to interact with a dynamically added swing component?


The following code snippet will create a new Button when "button" is pressed. I'm wondering if there's any way to assign a name, Action Listener, or any other properties to this new button in order to use it.

    button.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            panel.add(new JButton("Hello"));
            frame.revalidate();
            frame.repaint();
        }
    });

Example of what I'm looking for: On button press, create a new button that has a name and has an action performed when its clicked on. (Preferably I could dynamically make more than one button when clicked multiple times)


Solution

  • Put a call of test(); into the actionPerformed() of your first button.

    Every click on the first button will dynamicly create another button and name it individually. Every of these buttons also can dynamicly create individually named buttons.

    //The counter is used to name the buttons individually
    //It doesn´t matter wich of the created buttons will call test()
    //any new button will have a different name than the other buttons
    public int counter;    
    
    public void test() {    
            JButton btn = new JButton();
            //Now you can edit the properties
            //btn.setLocation
            //btn.setSize
            //btn.setVisible
            //btn...
            btn.setText("Hello");
            btn.setName("Button" + counter);
            panel.add(btn);   
    
            //Add of listener is untested, but it should work like this
            btn.addActionListener(new ActionListener() {  
                @Override  
                public void actionPerformed(ActionEvent e) {
                    test();
                }
            });
    
            counter ++;
        }