Java 将 JButton 添加到 JPanel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4123230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:51:37  来源:igfitidea点击:

Add JButtons to JPanel

javauser-interfaceswingjpaneljbutton

提问by Flynn

I want to add a number of JButtonsto a JPanelusing a Forloop. When the user presses a button, the following code is run:

我想使用循环JButtons向 a添加多个。当用户按下按钮时,将运行以下代码:JPanelFor

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.

但是,当我按下按钮时,没有 JButton 被添加到 JPanel,但程序会打印出应该添加的适当数量的按钮。

Not sure what the problem is here =/

不知道这里有什么问题=/

采纳答案by Flynn

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

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

回答by Matti Lyra

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