gpt4 book ai didi

java - JTextField 已初始化但似乎为 null

转载 作者:行者123 更新时间:2023-12-01 18:20:28 25 4
gpt4 key购买 nike

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

我不确定是否可以将所有这些 JLabel 和 JTextField 保留为类成员,然后随意读取它们。

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).

如果您想要许多带有这些字段的面板,那么您需要创建一个自定义类来创建面板,然后文本字段和标签将成为该类的一部分,而不是您的主类。

关于java - JTextField 已初始化但似乎为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27788995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com