tell me the best way to create a jbutton that will create other buttons in java swing?

When you add or remove components from a JPanel, you need to make that JPanel redraw itself. Just adding or removing a component does not make this happen. Hence, after adding or removing a component from a JPanel, you need to call method revalidate followed by a call to repaint.

Refer to Java Swing revalidate() vs repaint()

Also note that the following line of your code is not required since the visible property is true by default.

b.setVisible(true);

Also, it is recommended to use a layout manager which means you don’t need to call method setBounds as you have in this line of your code.

b.setBounds(50,100,95,30);

EDIT

As requested, a sample application. Clicking on the Add button will add another button. Note that the ActionListener for the Add button is implemented as a method reference.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ButtonAd {
    private static final String  ADD = "Add";

    private JFrame  frame;
    private JPanel  buttonsPanel;

    private void addButton(ActionEvent event) {
        JButton button = new JButton("Added");
        buttonsPanel.add(button);
        buttonsPanel.revalidate();
        buttonsPanel.repaint();
    }

    private JPanel createAddButton() {
        JPanel addButtonPanel = new JPanel();
        JButton addButton = new JButton(ADD);
        addButton.addActionListener(this::addButton);
        addButtonPanel.add(addButton);
        return addButtonPanel;
    }

    private void createAndDisplayGui() {
        frame = new JFrame("Add Buttons");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createButtonsPanel(), BorderLayout.CENTER);
        frame.add(createAddButton(), BorderLayout.PAGE_END);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createButtonsPanel() {
        buttonsPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
        buttonsPanel.setPreferredSize(new Dimension(450, 350));
        return buttonsPanel;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new ButtonAd().createAndDisplayGui());
    }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top