将 JButton 添加到 JPanel

发布于 2024-09-30 23:45:21 字数 406 浏览 2 评论 0原文

我想使用 For 循环将多个 JButtons 添加到 JPanel 中。当用户按下按钮时,将运行以下代码:

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

但是,当我按下按钮时,不会将 JButton 添加到 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");
}

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 =/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北斗星光 2024-10-07 23:45:21

我已经解决了我的问题。我正在使用 NetBeans,显然“自由布局”不起作用,因此我将 JPanel 的布局设置为“网格布局”,瞧,按钮出现了

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

生活了然无味 2024-10-07 23:45:21

我会使用以下内容。

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

mainPanel.invalidate();
mainPanel.repaint();

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文