什么是使用initComponents();在java构造函数中?

时间:2013-12-11 15:09:55

标签: constructor

每次我创建JFrame时都会看到initComponents();在我的构造函数中。它是什么?如果我删除它将会发生什么?

2 个答案:

答案 0 :(得分:5)

initcomponents()是一种方法,NetBeans(我猜你正在使用它)swing Designer创建初始化组件(设置默认值等)。它与JFrame类没有任何关系。

您可以随时调用该方法(构造函数,其他方法)。对于Java,它就像任何其他方法一样。但是,NetBeans IDE在构造函数中调用它来控制通过Netbeans的GUI编辑器传递的参数。默认为private

您可以将其视为GUI编辑器和Java之间的连接。因此,如果删除它,可能您将无法使用NetBeans提供的功能来处理组件(这仍然可以)。

答案 1 :(得分:2)

To add to Artem's answer above:

Invariably, the initcomponents() initializes all of the Java swing components objects that your front-end GUI uses using the NetBeans GUI Builder.

These swing components are automatically generated in your Java class whenever you make changes to the design of your GUI using the GUI builder.

As a general rule of thumb, you should never change any aspect of the code within this method as this method is inextricably linked to the front-end NetBeans GUI builder. The image below outlines the NetBeans GUI design builder. A user can quickly jump between the design front-end by clicking on the DESIGN button and also the source by clicking on the SOURCE button respectively

enter image description here

By clicking on the source button (outlined below), you will see the auto generated initcomponents() containing all of the swing components

enter image description here

the following link provides very good quick start guide to the essentials of NetBeans GUI builder: Designing a Swing GUI in NetBeans