我可以通过将成员指针传递给方法并在方法中分配它来初始化成员指针吗?

Can I initialize a member pointer by passing it to a method and allocating it in the method?

我有一个 JFrame 和一堆 JTextFormattedField 字段。每个 JTextFormattedField 的初始化都是相同的,所以我想为每个 JTextFormattedField 调用一个私有方法。这就是我试图做的:

JFrame初始化:

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

以及文本域初始化方法:

private JFormattedTextField addCharTextField (JFormattedTextField textField, FocusAdapter focusListener) {
    textField = new JFormattedTextField();
    textField.addFocusListener(focusListener);
    textField.setEditable(false);
    textField.setColumns(10);
    return textField;
}

我认为在传递给另一个方法后分配成员变量可能有问题。稍后在我的程序中,当我尝试访问 m_textField1 时,我得到了 NullPointerException。垃圾收集器是否删除 addCharTextField 末尾的 JFormattedTextField?除了在 JFrame 初始化例程中重新分配 JFormattedTextField 之外,有没有办法解决这个问题?即使只是为了美观,我真的希望 JFrame 初始化方法中每个成员变量的初始化只占用一行代码。

针对这个被视为重复的问题进行编辑:我的问题是:"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?"(再次是的,但很丑)。在另一个问题中选择的答案是这个被认为是重复的,但没有回答这两个问题中的任何一个。现在,在深入研究了其他一些答案并阅读了此处的评论之后,我终于能够拼凑出 Java 中发生的事情。但这并不会使这个问题重复。

就其价值而言,问题是 C++ 'new' 和 Java 'new' 的根本区别,这让我感到困惑。考虑到有多少其他语法 Java 从 C++ 借用而在用法上没有太大差异,我花了一些时间来理解 'new' 用法之间的差异。

没有。 Java 是按值传递。您对传递的参数所做的更改不会应用到原始参数中。