运行时无法将 JButton 添加到 JPanel

发布于 2024-12-13 01:40:32 字数 400 浏览 0 评论 0原文

我想在单击按钮后将 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 技术交流群。

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

发布评论

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

评论(3

苏大泽ㄣ 2024-12-20 01:40:32

您的代码对于标准 Swing JComponents 是正确的,

1) 是 < code>totalPane 已初始化

2) 是否将 totalPane 添加到容器中

3) totalPane 在容器中可见

4) 是否存在 BorderLayouttotalPane 定义,否则就在那里FlowLayout 默认情况下,

您可以简单地通过添加 边框 (totalPane.setBorder(BorderFactory.createLineBorder(Color. red));) 到 totalPane

your code is correct for standard Swing JComponents,

1) is totalPane initialized

2) is totalPane added to the Container

3) is totalPane visible in the Container

4) is there BorderLayout defined for totalPane, othervise is there FlowLayout by default

you can simply to test it by add Borders (totalPane.setBorder(BorderFactory.createLineBorder(Color.red));) to the totalPane

自由如风 2024-12-20 01:40:32

您添加按钮的代码是正确的,尽管您对 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?

迷爱 2024-12-20 01:40:32

请调试您的代码并检查您的方法是否被执行。如果不是,那么我们就知道问题所在,您必须确保您的方法被执行。

请注意,您的方法还有一种替代方法,您可以在初始化时创建按钮并将其可见性设置为 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.

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