javabuttondynamicruntimecreation

Creating Buttons during runtime in Java


I want to add a number of Buttons to my Java application based on an array. Say if there are 10 objects in an array, I want to create 10 buttons. If I delete 2 objects in the array the buttons should also get deleted. I thought about 3 things to go on about this problem.

A for loop - but I think the buttons would just exist inside the loop and also I would not know how to name the buttons (the variable name not the label).
A Thread
A seperate class

I have no idea how I would do that though.

Can I actually name variables through loops? Are any of my ideas practicable?


Solution

  • If you add a button to a JPanel it will survive outside the for loop, so don't worry about it. Create a JPanel just for your buttons and keep track of those you add using an ArrayList<JButton>, so you'll be able to delete them as you need. To delete them from the panel, refer to this answer. Remember to repaint (=refresh) the JPanel.

    JButton button1 = ...;
    
    // Add it to the JPanel
    // https://stackoverflow.com/questions/37635561/how-to-add-components-into-a-jpanel
    
    ArrayList<JButton> buttons = new ArrayList<>();
    buttons.add(button1);
    
    // Other stuff...
    
    // It's time to get rid of the button
    JButton theButtonIWantToRemove = buttons.get(0);
    buttons.remove(0);
    
    //Get the components in the panel
    Component[] componentList = panel.getComponents();
    
    //Loop through the components
    for(Component c : componentList){
        //Find the components you want to remove
        if(c == theButtonIWantToRemove){
            //Remove it
            panel.remove(c);
        }
    }
    
    //IMPORTANT
    panel.revalidate();
    panel.repaint();