Access Components Created in IntelliJ GUI Designer

Although I used Swing before I never used a GUI constructor, and I had problems accessing the components, which I reset to my panel from my source code.

I created a new project and decided to create a GUI form. Then I created the main method using the "generate" parameter, and now I have this code in the file "helloWorld.java".

public class helloWorld { private JPanel myForm; private JLabel text; public static void main(String[] args) { JFrame frame = new JFrame("helloWorld"); frame.setContentPane(new helloWorld().myForm); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(800, 600)); frame.pack(); frame.setVisible(true); } } 

Then I added JLabel in the constructor with the name of the title field, which added an attribute to the head of my helloWorld class. Now I want to set the text by the name of the field after starting the program.

If I create an instance of JLabel with a new line as an argument and add it to my JFrame, then the program will fail with an exceptional exception.

If I create a JLabel with no arguments and call setText on it and then redraw it on a JFrame, nothing happens.

I can guess some problem in one line: how do you access the components that I created using the GUI designer?

+8
java user-interface intellij-idea swing
source share
2 answers

First, IntelliJ is a little different in that it hides a lot of code templates for you, so your source code looks simpler than what really happens under the hood.

Basically, when you use the IntelliJ GUI builder, you get the source code that matches your form, which looks like this:

 public class DialogEditView { private JPanel mainPanel; private JLabel labelDescription; private JLabel labelExample; private JComboBox comboboxDEJC; } 

To have access to them, you can simply add getters to this source file:

 public class DialogEditView { private JPanel mainPanel; private JLabel labelDescription; private JLabel labelExample; private JComboBox comboboxDEJC; public JPanel getMainPanel() { return mainPanel; } // etc. } 

Again, IntelliJ either modifies the source code or automatically modifies the class files for you (you can go to "Settings / GUI Builder" to check the two options and see what they do).

How to access the components that I created using the designer GUI?

You can go to the source code file corresponding to your GUI and add getters. Be sure to list your components ...

+11
source share

The automatically generated initialization code in your binding class is as follows:

  private void $$$setupUI$$$() {} 

For more information on IntelliJ initialization code, see the Jetbrains documentation: Creating Form Initialization Code

0
source share

All Articles