开发者

Add JButtons to JPanel

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");
}

How开发者_JAVA技巧ever, 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 =/


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


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜