我不明白我的代码中发生了什么,当我触发一个带有附加动作侦听器的按钮时,即使所有字段都包含文本,阅读JTextField getText()值显示为null。此外,当我调试代码并在该行之前停止时,JTextField对象也显示为空,就像它从未初始化过一样。JTextField被初始化,但似乎为空
我不确定是否可以将所有这些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;
}
}
Java是通过值,不通过引用。将'manufacturerTextField'的值传递给方法不可能初始化它。 –
@DavidWallace是不是一个有效的方式来初始化该字段?我写了一个单独的方法来做到这一点(initialiseField()),所以我可以避免为每个字段重复相同的代码(在我的实际代码中有更多的代码)。 – kacpr
您没有初始化该字段。您将'null'传入了一个方法,该方法创建了一个新字段,但未将其分配给'manufacturerTextField'。 –