JTextField 已初始化但似乎为空

JTextField is initialised but appears to be null

我不明白我的代码中发生了什么,当我触发带有附加动作侦听器的按钮时,读取 JTextField getText() 值显示为 null,即使所有字段都包含文本。此外,当我调试代码并在此行之前停止时,JTextField 对象也显示为 null,就像它从未在一开始就被初始化一样。

我不确定我是否可以将所有这些 JLabel 和 JTextField 保留为 class 成员,然后自由地阅读它们。

public class EditPartGUI extends JFrame {
    private JLabel manufacturerLabel;
    private JTextField manufacturerTextField;

    private JButton submit;
    private ActionListener submitListener;

    public EditPartGUI(Part part) {
        JPanel panel = new JPanel();
        this.setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

        panel.add(initialiseField("Manufacturer: ", manufacturerLabel, part.getManufacturer(), manufacturerTextField));

        JPanel sub = new JPanel();
        submit = new JButton("Submit");
        submitListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println(submit().toString());
            }
        };
        submit.addActionListener(submitListener);

        sub.add(submit);
        panel.add(sub);

        this.add(panel);
    }

    public JPanel initialiseField(String label, JLabel contentLabel, String value, JTextField contentTextField) {
        JPanel contentPanel = new JPanel();
        contentLabel = new JLabel(label, JLabel.TRAILING);

        contentTextField = new JTextField(10);
        contentTextField.setText(value);
        contentLabel.setLabelFor(contentTextField);

        contentPanel.add(contentLabel);
        contentPanel.add(contentTextField);
        return contentPanel;
    }

    public Part submit() {
        Part p = new Part();
        p.setManufacturer(this.manufacturerTextField.getText()); // <---- this is where NullPointerException shows
        return p;
    }
}

I'm not sure whether I can keep all these JLabel and JTextField as class members and then just freely read from them.

是的,你可以,这就是你的问题的解决方案。

当你

时,只需使用以下内容
//private JTextField manufacturerTextField;
private JTextField manufacturerTextField = new JTextField();

并且不要尝试在 initialiseField() 方法中创建文本字段。当然你需要对标签做同样的事情。

so I could avoid repeating the same code for each field (there are a lot more of them in my actual code).

如果您希望有许多包含这些字段的面板,那么您需要创建自定义 class 来创建面板,然后文本字段和标签将成为该面板的一部分 class,不是你的主要 class.

问题是,您假设方法 initialiseField 正在将参数 contentTextField 分配给 manufactererTextField。这在 Java 中不起作用,正如 David Wallace 已经说过的那样。

如果您想避免重复相同的代码,请尝试创建一个 returns 初始化 TextField 的方法,并在构造函数中分配它。