Add JButtons to JPanel

24,368

Solution 1

I've solved my problem. I'm using NetBeans and apparently Free Layout doesn't work, so I set the JPanel's layout to Grid Layout and voila, the buttons appear

Solution 2

I would use the following.

for (i = 0; i < 10; i++) {
    mainPanel.add(new JButton("Button text"));
    System.out.println("Added: " + (i + 1) + "buttons");
}

mainPanel.invalidate();
mainPanel.repaint();
Share:
24,368
Flynn
Author by

Flynn

Updated on November 15, 2020

Comments

  • Flynn
    Flynn over 3 years

    I want to add a number of JButtons to a JPanel using a For loop. When the user presses a button, the following code is run:

    for (i = 0; i < 10; i++)
    {
      JButton aButton = new JButton();
      mainPanel.add(aButton);
      mainPanel.revalidate();
      mainPanel.repaint();
      System.out.println("Added: " + (i + 1) + "buttons");
    }
    

    However, when I press the button, no JButtons are added to the JPanel, but the program prints the appropriate number of buttons that should be added.

    Not sure what the problem is here =/

  • Rémi Vennereau
    Rémi Vennereau over 13 years
    if you need invalidate and repaint you are most likely doing something wrong?
  • Matti Lyra
    Matti Lyra over 13 years
    You still don't want to be calling the repaint method inside the for loop. There is no reason to repaint the panel ten times.
  • Flynn
    Flynn over 13 years
    Thanks. Will repaint outside the loop
  • camickr
    camickr over 13 years
    All you need is revalidate(). This will cause the layout manager to be invoked.