运行时无法将 JButton 添加到 JPanel
我想在单击按钮后将 JButton 添加到 JPanel,所以这是我的代码:
JButton testButton = null;
private void sendmessageButtonActionPerformed(java.awt.event.ActionEvent evt) {
testButton = new JButton();
totalPane.add(testButton,BorderLayout.CENTER);
totalPane.revalidate();
totalPane.repaint();
}
我正在使用 Netbean GUI 构建器。当我点击时,什么也没有发生。有人可以帮助我吗?
I want to add a JButton to a JPanel after a click on a button so here is my code :
JButton testButton = null;
private void sendmessageButtonActionPerformed(java.awt.event.ActionEvent evt) {
testButton = new JButton();
totalPane.add(testButton,BorderLayout.CENTER);
totalPane.revalidate();
totalPane.repaint();
}
I am using the Netbean GUI builder. When I click, nothing happens. Could anyone help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码对于标准 Swing JComponents 是正确的,
1) 是 < code>totalPane 已初始化
2) 是否将
totalPane
添加到容器中3)
totalPane
在容器中可见4) 是否存在 BorderLayout 为
totalPane
定义,否则就在那里FlowLayout 默认情况下,您可以简单地通过添加 边框 (
totalPane.setBorder(BorderFactory.createLineBorder(Color. red));
) 到totalPane
your code is correct for standard Swing JComponents,
1) is
totalPane
initialized2) is
totalPane
added to the Container3) is
totalPane
visible in the Container4) is there BorderLayout defined for
totalPane
, othervise is there FlowLayout by defaultyou can simply to test it by add Borders (
totalPane.setBorder(BorderFactory.createLineBorder(Color.red));
) to thetotalPane
您添加按钮的代码是正确的,尽管您对 repaint() 的调用不会实现任何目标 - revalidate() 就足够了。
我的猜测是您的 sendmessageButtonActionPerformed 方法从未被调用。它看起来不像是 ActionListener 或任何其他侦听器的一部分的任何方法。如何在触发添加的按钮上设置 ActionListener?
Your code for adding the button is correct, although your call to repaint() wont achieve anything - revalidate() is enough.
My guess is that your sendmessageButtonActionPerformed-method is never invoked. It does not look like any method that is part of ActionListener or any other listener. How have you set up the ActionListener on the button that triggers the add?
请调试您的代码并检查您的方法是否被执行。如果不是,那么我们就知道问题所在,您必须确保您的方法被执行。
请注意,您的方法还有一种替代方法,您可以在初始化时创建按钮并将其可见性设置为 false。当您需要它时,您可以使其可见。但是,您的方法应该有效。
Please debug your code and check whether your method is executed. If it isn't, then we know the problem and you must make sure your method is executed.
Note that there is an alternative to your approach, you can create your button at initialize time and set its visibility to false. When you need it you can make it visible. However, your approach should work.