Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在netbeans的运行时添加swing组件_Java_Swing_Components - Fatal编程技术网

Java 在netbeans的运行时添加swing组件

Java 在netbeans的运行时添加swing组件,java,swing,components,Java,Swing,Components,我已经学习了核心java,刚刚开始使用netbeans,但我在项目运行时尝试添加按钮、标签等组件时遇到了一个问题。我在google上搜索了它,但我学习的示例包括在其中使用面板的额外开销,,,,但是为什么我不能在运行时创建组件,因为我是在像记事本这样的简单编辑器中创建组件的,如下所示 JButton b4=new JButton("ok"); add b4; 它不起作用。要在运行时添加Swing框架元素,您需要有一个JFrame来添加元素。JFrame只是一个窗口,就像您使用的任何其他窗口(就像

我已经学习了核心java,刚刚开始使用netbeans,但我在项目运行时尝试添加按钮、标签等组件时遇到了一个问题。我在google上搜索了它,但我学习的示例包括在其中使用面板的额外开销,,,,但是为什么我不能在运行时创建组件,因为我是在像记事本这样的简单编辑器中创建组件的,如下所示

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

它不起作用。

要在运行时添加Swing框架元素,您需要有一个JFrame来添加元素。JFrame只是一个窗口,就像您使用的任何其他窗口(就像NetBeans一样),它有一个名为
add(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,那么上面的代码应该可以工作。祝你好运

你把哪个类划分为子类?你收到错误信息了吗?你能添加更多的代码吗?是另一个类似的问题和我的答案,虽然它不使用NetBeans GUI builder,但我不建议您如果真的想学习java,它会向您展示动态添加组件所需的正确逻辑。@DavidKroukamp:为什么不这样做?当我从一个简单愚蠢的编辑器跳到这个出色的IDE时,我一直在想netbeans现在会让我的工作变得轻松一些D@t3nIDE仍然是愚蠢的,它只是添加了一些很好的特性,使索引更容易,但是在运行时,IDE是愚蠢的irrelevant@t3n在Netbeans设计器中,您将组件添加到什么中??您必须将它们添加到某个sortnot容器中,请阅读评论,阅读链接线程,运行这些代码,然后修改此帖子或删除(我这边没有任何操作,接受您的21点)@mKorbel我道歉。你能澄清一下吗?@mKorbel:我这边也一样……澄清一下please@t3n我的回答有意义吗,或者我应该添加到其中以作进一步解释吗?没有,您已经很好地解释了您的部分,但我想问的是在运行时在netbeans IDE中添加组件…..)。。。你错过的那个netbean东西:)