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();
Author by
Flynn
Updated on November 15, 2020Comments
-
Flynn over 3 years
I want to add a number of
JButtons
to aJPanel
using aFor
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 over 13 yearsif you need invalidate and repaint you are most likely doing something wrong?
-
Matti Lyra over 13 yearsYou 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 over 13 yearsThanks. Will repaint outside the loop
-
camickr over 13 yearsAll you need is revalidate(). This will cause the layout manager to be invoked.