Barbell
Barbell

Reputation: 314

Using a function in Initcomponents()

I am making a JFrame application in Java , I'm using the Application designer to insert components in my JFrame. In a Jtextarea , I would like to display some text but that text is returned by a function that I wrote in my class. So I thought I can just call the function in the JTextarea value in the initcomponents() which manage the code for my gui components. But the initcomponent method can not be modified(highlighted in grey). Is there a way to do this?

public String yes() {
    return "voila";
}

Is there a way to do something like this ?

private void initcomponent() {
    jTextArea1.setText("some text" + yes());
}

Upvotes: 0

Views: 3159

Answers (2)

Héctor M.
Héctor M.

Reputation: 2392

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.

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 {

public NewJFrame() {
    initComponents();
    myInitComponents();
}

public void myInitComponents() 
{
   jTextArea1.setText("some text"+yes());
}

public String yes(){
    return "voila";
}

Upvotes: 1

MatheM
MatheM

Reputation: 811

The initComponents() method is generated by the IDE, each time you build the project it is regenerated (from separate xml). You have to "tell" the IDE that you are adding custom code.

  • Go to your GUI editor, Click on the JTextArea component

enter image description here

  • select Properties (in the sidebar under the palette), find text property, click ellipsis (button with three dots)

enter image description here

  • from the dialog that pops up select custom code, type the code that returns the string you want.

enter image description here

Upvotes: 1

Related Questions