在 JPanel 中插入按钮 [英] Insert Button in JPanel
问题描述
我在 Java 中使用了 Swing,我需要创建一个 JButton 并将其放入 JPanel.
I am using swing in Java and I need to create a JButton and put it in a JPanel.
我阅读了教程,我做到了:
I reed tutorials and I did this:
public void crearNuevaMiga(String nombre)
{
JButton nuevo = new JButton(nombre);
this.MigasDePan.add(nuevo);
nuevo.setVisible(true);
nuevo.setLocation(new Point(migaX, migaY));
System.out.println(nuevo.getLocation().x + " "+ nuevo.getLocation().y);
migaX = migaX-avanceMigas;
}
我这样做了,当我调用该函数时,我看不到按钮.我在 NetBeans 的设计者处放了一个按钮并获得 X 和 Y 位置.然后,在变量 migaX 和 migaY 中,我放置了 X 和 Y 位置,因此按钮需要位于相同的位置,但它不在那里.
I do that and when I call the function, I cant see the button. I put a button with the designer of NetBeans and get X and Y Location. Then, in the variables migaX and migaY I put that X and Y Location, so the button need to be in the same position, but it is not there.
有人知道为什么吗?也许这样放置位置不正确?
Anyone knows why? Maybe putting the location in that way is not correct?
感谢您的时间!
MigasDePan 是我的 JPanel
MigasDePan is my JPanel
推荐答案
默认情况下,组件的大小为 (0, 0),因此没有可绘制的内容.
By default components have a size of (0, 0) so there is nothing to paint.
当您向可见 GUI 动态添加按钮时,您需要调用布局管理器,以便布局管理器可以确定组件的大小/位置.
When you dynamically add a button to a visible GUI you need to invoke the layout manager so the components size/location can be determined by the layout manager.
基本代码为:
panel.add(...);
panel.revalidate();
panel.repaint();
这篇关于在 JPanel 中插入按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!