Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing components created in GUI designer on IntelliJ

Although I've used Swing before I've never used a GUI designer and I'm having trouble accessing components I've dropped onto my panel from within my source code.

I created a new project and chose to create a GUI form. I then created the main method using the 'generate' option and now I have this code in my 'helloWorld.java' file.

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);
    }
}

I then added a JLabel in the designer with the field name title which added an attribute to the head of my helloWorld class. I now want to set the text on the field name after the program has run.

If I create the JLabel instance with a new string as an argument and add it to my JFrame then the program crashes with a null pointer exception.

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

I guess to some up my problem in a single line: How do you access components that I have created using the GUI designer?

like image 708
Ashley Avatar asked Feb 03 '23 08:02

Ashley


1 Answers

First, IntelliJ is a bit special in that it hides a lot of the boilerplate code for you, so your source code looks actually simpler than what is really going on under the hood.

Basically, when you use the IntelliJ GUI builder, you end up with a source code corresponding to your form that looks like this:

public class DialogEditView {

    private JPanel mainPanel;
    private JLabel labelDescription;
    private JLabel labelExample;
    private JComboBox comboboxDEJC;

}

To be able to access these, you can simply add getters to that source file:

public class DialogEditView {

    private JPanel mainPanel;
    private JLabel labelDescription;
    private JLabel labelExample;
    private JComboBox comboboxDEJC;

    public JPanel getMainPanel() {
        return mainPanel;
    }

    // etc.

}

Once again, IntelliJ either modifies the source code or modifies the class files automagically for you (you can go in the Settings / GUI Builder to test the two options and see what they do).

How do you access components that I have created using the GUI designer?

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

like image 137
TacticalCoder Avatar answered Feb 05 '23 16:02

TacticalCoder