Question

I am building a GUI and want to access an SWT button that is initialized in the constructor from another method. is that possible?

public class MaskeSection {
 final org.eclipse.swt.widgets.Group PRBS_EXT;
     Button PRBS;
 public MaskeSection(Group Part1){

     PRBS_EXT = new org.eclipse.swt.widgets.Group(Part1, SWT.NONE);


             final org.eclipse.swt.widgets.Button PRBS = new org.eclipse.swt.widgets.Button(PRBS_EXT, SWT.RADIO);
     PRBS.setEnabled(false);
     }

 public void setPRBS(){
             PRBS.setSelection(true);
 }

When I want to call the setPRBS(), it gives me Null Pointer Exception because PRBS = Null I suppose, but PBS is already assigned in the constructor.

Was it helpful?

Solution

You are defining a local variable with the same name as the field in your constructor. So you're basically shadowing the field variable which remains uninitialized.

This is how you can solve it:

public class MaskeSection {
    private Group myGroup;
    private Button myButton;

    public MaskeSection(Group part) {
        myGroup = new Group(part, SWT.NONE);
        myButton = new Button(myGroup, SWT.RADIO);
        myButton.setEnabled(false);
    }

    public void setPRBS(boolean selected) {
        myButton.setSelection(selected);
    }
}

You should really read up on your Java basics. Here is a tutorial about member variables (fields).

Also please stick to the Java naming conventions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top