Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify/add code to the initComponents() method in Java using NetBeans?

Tags:

How to modify/add code to the initComponents() method in Java on NetBeans? When I try to add any line of code this area seems to be like readonly and it's highlighted in gray! It's for security probably, but I suppose there is a way to disable that.

like image 750
Ahmad Farid Avatar asked Mar 13 '10 11:03

Ahmad Farid


People also ask

How to modify initComponents in NetBeans?

If you right-click on the component in the Design View , and then click on " Customize Code " selection, you can modify the code in the InitComponent code.

What is Initcomponents () in Java?

initcomponents() is a method that NetBeans (I guess you are using it) swing Designer creates to initialise components (set default values etc.). It doesn't really have anything to do with the JFrame class. You can call the method whenever you like (constructor, other method). For Java, it is just like any other method.

How do I add a design editor in NetBeans?

Select Tools > Options from the menu to open it and then select the "JFormDesigner" page. See Preferences for details. You can also set project specific options in the NetBeans project dialog. Select File > Project Properties from the menu to open it and then expand the node "JFormDesigner" in the tree.


2 Answers

Yes the initComponents method is read only to keep full control for the IDE. You may add yours in the constructor right after initComponents.

public class NewJFrame extends javax.swing.JFrame {  /** Creates new form NewJFrame */ public NewJFrame() {     initComponents();     myInitComponents(); }  public void myInitComponents() { } 
like image 90
PeterMmm Avatar answered Sep 16 '22 15:09

PeterMmm


The initComponents() method is regenerated by the IDE as you create your UI in the GUI editor. The method is 'guarded' to prevent this regeneration from overwriting user written code.

There are a couple of ways to add code to this method, indirectly:

  1. Drop a new component onto the design editor 'canvas' for the window.

  2. Enter code as part of one of the following code properties: Pre-Creation Code, Post-Creation Code, Pre-Init Code, Post-Init Code, Post-Listener Code, Pre-Population Code, Post-Population Code and After-All-Set Code.

    There are a couple other code properties that do not alter the initComponents() method... but can be very useful: Pre-Declaration Code and Post-Declaration Code. alt text http://blogs.sun.com/vkraemer/resource/code-properties.png Note: the editor for these properties is not 'rich', so I would recommend creating methods in the "regular editor" that you just call in the initComponents().

You can modify the code in the initComponents() method by positioning or changing the 'regular' properties of the 'base panel' or controls.

like image 44
vkraemer Avatar answered Sep 16 '22 15:09

vkraemer