在 NetBeans 中,我使用 GUI 编辑器创建了一个 JFrame,并将 JPanel 放入该框架中。 目前,我正在尝试在类构造时在面板中创建一个新按钮。 这是我的代码,但我似乎无法让它工作。 (第一行制作按钮,其他行尝试显示它。)
this.jPanel2.add(new JButton("Test"),BorderLayout.NORTH);
this.jPanel2.validate();
this.jPanel2.revalidate();
this.jPanel2.repaint();
this.jPanel2.setVisible(true);
this.revalidate();
this.setVisible(true);
this.repaint();
我整晚都在谷歌上搜索,但似乎无法正常工作。
最佳答案
有时您没有看到按钮,这是布局管理器的问题(因为您没有为布局管理器设置正确的属性)。您可以通过禁用它来测试它:
this.jPanel2.setLayoutManager(null);
并为按钮设置边界 (JButton.setBounds()
)。
如果以上解决了您的问题,那么您需要查看您正在使用的 LayoutManager 设置的要求(另请参阅 Robin 的回答)。
执行此操作不需要对 validate()
、revalidate()
和 repaint()
的所有调用。
关于java - 如何动态添加JButton到JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9885855/