I have a JFrame
and a bunch of JTextFormattedField
fields. The initialization for each JTextFormattedField
is the same, so I'd like to have a private method that I call for each JTextFormattedField
. This is what I tried to do:
JFrame
Initialization:
myJFrame.getContentPane().add(addCharTextField(m_textField1, new textFieldFocusListener()), "cell 3 1 2 1,growx");
myJFrame.getContentPane().add(addCharTextField(m_textField2, new textFieldFocusListener()), "cell 3 2 2 1,growx");
myJFrame.getContentPane().add(addCharTextField(m_textField3, new textFieldFocusListener()), "cell 3 3 2 1,growx");
And the text field initialization method:
private JFormattedTextField addCharTextField (JFormattedTextField textField, FocusAdapter focusListener) {
textField = new JFormattedTextField();
textField.addFocusListener(focusListener);
textField.setEditable(false);
textField.setColumns(10);
return textField;
}
I think there's might be problem with allocating the member variable after being passed to another method. Later on in my program when I try to access m_textField1
, I get a NullPointerException. Does the garbage collector delete the JFormattedTextField
at the end of addCharTextField
? Is there a way around this, besides allocating the JFormattedTextField
back in the JFrame
initialization routine? Even if just for aesthetic purposes, I really wanted the initialization for each member variable in the JFrame
initialization method to take up just one line of code.
Edit in response to this question being regarded as a duplicate: My questions are: "Does the garbage collector delete the JFormattedTextField
at the end of addCharTextField
?" (The answer was yes) And "Is there a way around this, besides allocating the JFormattedTextField
back in the JFrame
initialization routine?" (again yes, but ugly). The chosen answer in the other question that this one is regarded as a duplicate does not answer either of those. Now after digging into some of the other answers, and reading the comments here, I was finally able to piece together what's going on in Java. But that does not make this question a duplicate.
For what it's worth, the problem is a fundamental difference in the C++ 'new' and the Java 'new' that was confusing me. Considering how much other syntax Java borrowed from C++ without big differences in usage, It took me a bit to wrap my head around around the differences between the 'new' usage.