【问题标题】:adding swing components at run time in netbeans [duplicate]在运行时在netbeans中添加swing组件[重复]
【发布时间】:2012-12-19 05:18:25
【问题描述】:

我已经学习了核心 java 并且刚刚开始使用 netbeans,但是当我试图在我的项目的运行时添加按钮、标签等组件时,我陷入了困境.我在谷歌上搜索它,但我研究的例子包括在其中使用面板的一些额外开销,,,但是为什么我不能在运行时创建组件,因为我在像 记事本如下

JButton b4=new JButton("ok");
add b4;

它不工作。

【问题讨论】:

  • 你子类化了哪个类?您收到错误消息吗?你能添加更多代码吗?
  • Here 是另一个类似的问题和我的回答,虽然它没有使用 NetBeans GUI builder,但我不建议如果你真的想学习 java,它确实向你展示了添加组件所需的正确逻辑动态的。
  • @DavidKroukamp:为什么不这样做呢?当我从一个简单的 DUMB 编辑器跳到这个出色的 IDE 时,我一直在想 netbeans 会减轻我的工作负担。:D
  • @t3n IDE 仍然很笨,它只是添加了一些不错的功能,使您的索引更容易,但在运行时,IDE 无关紧要
  • @t3n 在 Netbeans 设计器中,您要将组件添加到什么?您必须将它们添加到某种容器中

标签: java swing components


【解决方案1】:

要在运行时添加 Swing 框架元素,您需要有一个 JFrame 来添加元素。 JFrame 只是一个窗口,就像您使用的任何其他窗口一样(就像 NetBeans 一样),它有一个名为 add(Component comp) 的方法。该参数是您要添加到 JFrame 的任何 Swing 或 AWT 组件。这里有一些示例代码可以帮助您入门:

// This line creates a new window to display the UI elements:
JFrame window = new JFrame("Window title goes here");

// Set a size for the window:
window.setSize(600, 400);

// Make the entire program close when the window closes:
// (Prevents unintentional background running)
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// This makes it so we can position elements freely:
window.setLayout(null);

// Create a new button:
JButton b4 = new JButton("ok");

// Set the location and size of the button:
b4.setLocation(10, 10);
b4.setSize(100, 26);

// Add the button to the window:
window.add(b4);

// Make the window visible (this is the only way to show the window):
window.setVisible(true);

希望对您有所帮助!我记得当我开始使用 Java 时,我强烈建议您先尽可能地精通非 GUI 相关的东西,但是如果您准备好使用 Swing,那么上面的代码应该可以工作。祝你好运!

【讨论】:

  • 不,请阅读评论,阅读链接线程,运行这些代码,然后修改此帖子或删除该帖子(我没有采取任何行动,接受您的 21 分)
  • @mKorbel 我很抱歉。你能澄清一下吗?
  • @mKorbel:我这边也是这样......请澄清
  • @t3n 我的回答是否有道理,或者我应该添加它以进一步解释吗?
  • 不,你已经很好地解释了你的部分,但我问的是在运行时在 netbeans IDE 中添加组件.. :)...你错过了 netbean 的东西..:)
猜你喜欢
  • 2013-08-18
  • 2014-01-23
  • 2014-02-14
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-30
相关资源
最近更新 更多