我试图在链表中获取我的一个对象的值之一,但在下面的行中收到了一个空指针异常:
txtyourname.setText(model.get(0).getYourname());
我知道变量名称与应用程序的上下文不匹配,但这是对以前项目的改编,编辑对话框选项是一个附加功能。
如有任何帮助,我们将不胜感激。
型号类别:
public class Model {
private LinkedList<Mat> Mat;
private String file="amey.xml";
int recordnum =1;
@SuppressWarnings("unchecked")
public Model() {
Mat = new LinkedList<Mat>();
boolean readOk = true;
try{
XMLDecoder decoder = new XMLDecoder (new FileInputStream(file));
Mat = (LinkedList<Mat>) decoder.readObject();
decoder.close();
}catch (Exception e) {
//File Not Found
readOk=false;
}
if(!readOk){
Mat = new LinkedList<Mat>();
}
// mats = new Mat[25];
// numberOfMats = 0;
initialiseData();
readTextData();
}
public void readTextData(){
File folder = new File("C:/Users/Adam Worrallo/Desktop/Test Files/");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
try {
String content = FileUtils.readFileToString(file);
String [] data = content.split("\\"); //splits into records
for(int i1=0; i1 < data.length; i1++){
String [] data2 = data[i1].split("n"); //splits into lines
String [] one = data2[0].split(":");
String [] two = data2[1].split(":");
String [] three= data2[2].split(":");
String [] four= data2[3].split(":");
String [] five= data2[4].split(":");
String [] six= data2[5].split(":");
String [] seven= data2[6].split(":");
String [] eight= data2[7].split(":");
Mat m = new Mat(one[1].trim(),two[1].trim(),three[1].trim(),four[1].trim(),
five[1].trim(),six[1].trim(),seven[1].trim(),eight[1].trim());
//loop through list and use equals method to check the data isnt already
//in the list
if(Mat.contains(m)){
continue;
}else{
Mat.add(m);
recordnum++;
}
// for(int a=0; a <Mat.size(); a++){
// if(Mat.get(a).equals(m)){
// break;
// }else if(a==Mat.size() && !Mat.get(a).equals(m)){
// Mat.add(m);
// recordnum++;
// }
// }
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* do somthing with content */
}
}
}
public void readFileData(File f){
if (f.isFile() && f.getName().endsWith(".txt")) {
try {
String content = FileUtils.readFileToString(f);
String [] data = content.split("\\"); //splits into records
for(int i1=0; i1 < data.length; i1++){
String [] data2 = data[i1].split("n"); //splits into lines
//get the users input by splitting it from titles
String [] one = data2[0].split(":");
String [] two = data2[1].split(":");
String [] three= data2[2].split(":");
String [] four= data2[3].split(":");
String [] five= data2[4].split(":");
String [] six= data2[5].split(":");
String [] seven= data2[6].split(":");
String [] eight= data2[7].split(":");
Mat m = new Mat(one[1].trim(),two[1].trim(),three[1].trim(),four[1].trim(),
five[1].trim(),six[1].trim(),seven[1].trim(),eight[1].trim());
if(Mat.contains(m)){
continue;
}else{
Mat.add(m);
recordnum++;
}
// for(int a=0; a <Mat.size(); a++){
// if(Mat.get(a).equals(m)){
// break;
// }else if(a==Mat.size() && !Mat.get(a).equals(m)){
// Mat.add(m);
// recordnum++;
// }
// }
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* do somthing with content */
}
}
/**
* @param mat - the object to add
* @return Starts the add mat command, opening the add mat GUI.
*/
public boolean addItem(Mat mat) {
return Mat.add(mat);
}
/**
*
* @param index - if the index is less than zero it does nothing
* @return if the index is valid it returns the delete command to the mat class which removes the record.
*/
public boolean deleteItem(int index) {
if ((index < 0) || (index >= Mat.size()))
return false;
Mat mat;
mat = Mat.remove(index);
if (mat == null)
return false;
return true;
}
/**
*
* @return writes the data to the xml file for storage.
*/
public boolean savingmats(){
boolean savedOk=true;
try{
XMLEncoder encoder = new XMLEncoder (new FileOutputStream(file));
encoder.writeObject(Mat);
encoder.close();
}catch (Exception e) {
savedOk=false;
}
return savedOk;
}
/**
*
* @return returns an array containing all mats in the database.
*/
public Mat[] getAllMats() {
Mat[] allmats = new Mat[Mat.size()];
allmats = Mat.toArray(allmats);
return allmats;
}
/**
* @return sorts the mats alphabetically by their country of origin.
*/
public void sortbyDate(){
matDateComparator comp = new matDateComparator();
Collections.sort(Mat, comp);
}
/**
* @return sorts the mats numerically by their number of layers.
*/
public void sortbyLocation() {
matLocationComparator comp = new matLocationComparator();
Collections.sort(Mat, comp);
}
//
/**
*
* @param target
* @return returns any record with an exhibition location equal to what the user entered.
*/
public int sequentialSearchForName(String target){
int index = 0;
for(Mat m : Mat){
if (m.getYourname().equalsIgnoreCase(target))
return index;
index++;
}
return -1;
}
/**
*
* @param target
* @return returns any record with a country of origin equal to what the user entered.
*/
public int sequentialSearchforLocation(String target){
int index = 0;
for(Mat m : Mat){
if (m.getLocation().equalsIgnoreCase(target))
return index;
index++;
}
return -1;
}
/**
*
* @param index
* @return returns the record with the index number requested.
*/
public Mat get(int index){
if ((index < 0) || (index >= Mat.size()))
return null;
return Mat.get(index);
}
private void initialiseData() {
/**
Mat first = new Mat("test name", "test depot","24-06-2013","time","location","details",
"outcome","did");
addItem(first);
Mat second = new Mat("adam","Quinton","24-06-2013","time","Quinton","none",
"nothing happened","nothing");
addItem(second);
// TODO Add code here to initially add 2 Mat objects to the array
// Don't forget to change the value of numberOfMats to 2
/**
* Use the following values: Object 1: countryOfOrigin = "Persia" layers
* = 2 hasWear = false pileDepth = 1.43 material = "rubber" isAbsorbant
* = true museumZone = "Purple Room" isOnDisplay = true
*
* Object 2: countryOfOrigin = "Russia" layers = 3 hasWear = true
* pileDepth = 0.66 material = "reeds" isAbsorbant = false museumZone =
* "Green Room" isOnDisplay = false
*
*/
}
public int getRecordnum() {
return recordnum;
}
}
编辑对话框类:
@SuppressWarnings("serial")
public class EditDialog extends javax.swing.JDialog {
private JPanel mainPanel, inputPanel, controlsPanel, closersPanel;
private JLabel lblTitle, lblyourname, lblyourdepot, lbldate,lbltime, lbllocation, lbldetails, lbloutcome, lbldid;
private JTextField txtyourname, txtyourdepot, txtdate, txttime, txtlocation, txtdetails,txtoutcome,txtdid;
private JButton btnOK, btnCancel;
private JLabel lblError;
// labels for spacers
private JLabel lblNorth, lblEast, lblWest;
// attribute for holding details
private Mat mat;
private Model model;
private int chosenRecord;
//this sets out the main window
public EditDialog(JFrame frame, int index) {
super(frame);
// Prevent the user from closing the dialogue
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
setResizable(false);
setTitle("Add A New Close Call");
setModal(true);
setSize(600, 430);
initGUI();
setVisible(true);
chosenRecord = index;
}
//this initialises the componenets of the gui
private void initGUI() {
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
setContentPane(mainPanel);
// Inner panels
inputPanel = new JPanel();
inputPanel.setLayout(new BorderLayout());
mainPanel.add(inputPanel, BorderLayout.CENTER);
controlsPanel = new JPanel();
controlsPanel.setLayout(new GridLayout(8,2));
inputPanel.add(controlsPanel, BorderLayout.CENTER);
closersPanel = new JPanel();
mainPanel.add(closersPanel, BorderLayout.SOUTH);
lblTitle = new JLabel("Please Enter The Details For The Close Call");
mainPanel.add(lblTitle, BorderLayout.NORTH);
lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
lblTitle.setFont(new java.awt.Font("Arial",1,16));
// Data entry controls and labels
lblyourname = new JLabel("Your Name: ");
lblyourname.setHorizontalAlignment(SwingConstants.LEFT);
controlsPanel.add(lblyourname);
txtyourname = new JTextField();
controlsPanel.add(txtyourname);
lblyourdepot = new JLabel("Your Depot: ");
lblyourdepot.setHorizontalAlignment(SwingConstants.LEFT);
controlsPanel.add(lblyourdepot);
txtyourdepot = new JTextField();
controlsPanel.add(txtyourdepot);
lbldate = new JLabel("Date Of Incident:");
lbldate.setHorizontalAlignment(SwingConstants.LEFT);
controlsPanel.add(lbldate);
txtdate = new JTextField();
controlsPanel.add(txtdate);
lbltime = new JLabel("Time Of Incident:");
lbltime.setHorizontalAlignment(SwingConstants.LEFT);
controlsPanel.add(lbltime);
txttime = new JTextField();
controlsPanel.add(txttime);
lbllocation = new JLabel("Specific Location Of Incident:");
lbllocation.setHorizontalAlignment(SwingConstants.LEFT);
controlsPanel.add(lbllocation);
txtlocation = new JTextField();
controlsPanel.add(txtlocation);
lbldetails = new JLabel("Incident Details:");
lbldetails.setHorizontalAlignment(SwingConstants.LEFT);
controlsPanel.add(lbldetails);
txtdetails = new JTextField();
controlsPanel.add(txtdetails);
lbloutcome = new JLabel("Potential Outcome: ");
lbloutcome.setHorizontalAlignment(SwingConstants.LEFT);
controlsPanel.add(lbloutcome);
txtoutcome = new JTextField();
controlsPanel.add(txtoutcome);
lbldid = new JLabel("What You Did: ");
lbldid.setHorizontalAlignment(SwingConstants.LEFT);
controlsPanel.add(lbldid);
txtdid = new JTextField();
controlsPanel.add(txtdid);
txtyourname.setText(model.get(0).getYourname());
// label for error messages
lblError = new JLabel(" ");
lblError.setHorizontalAlignment(SwingConstants.CENTER);
lblError.setForeground(Color.RED);
inputPanel.add(lblError, BorderLayout.SOUTH);
// Buttons
btnOK = new JButton("OK");
btnOK.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// validate user input, only close dialogue if OK
if(check())
setVisible(false);
}
});
closersPanel.add(btnOK);
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
mat = null;
setVisible(false);
}
});
closersPanel.add(btnCancel);
// spacers
lblWest = new JLabel(" ");
inputPanel.add(lblWest, BorderLayout.WEST);
lblEast = new JLabel(" ");
inputPanel.add(lblEast, BorderLayout.EAST);
lblNorth = new JLabel(" ");
inputPanel.add(lblNorth, BorderLayout.NORTH);
}
public Mat getMat() {
return mat;
}
//this checks that appropriate details have been entered and highlights any errors for the user to see
public boolean check() {
boolean valid = true;
String name;
String depot;
String date;
String time;
String location;
String details;
String outcome;
String did;
// clear any previous error indications
lblyourname.setForeground(Color.BLACK);
lblyourdepot.setForeground(Color.BLACK);
lbldate.setForeground(Color.BLACK);
lbltime.setForeground(Color.BLACK);
lbllocation.setForeground(Color.BLACK);
lbldetails.setForeground(Color.BLACK);
lbloutcome.setForeground(Color.BLACK);
lbldid.setForeground(Color.BLACK);
// Check Country Of Origin is not empty
name = txtyourname.getText();
if(name.length() < 1){
// set error condition found
valid = false;
// show where error is located
lblyourname.setForeground(Color.RED);
}
depot = txtyourdepot.getText();
if(depot.length() < 1){
valid = false;
lblyourdepot.setForeground(Color.RED);
}
date = txtdate.getText();
if(date.length() < 1){
valid = false;
lbldate.setForeground(Color.RED);
}
time = txttime.getText();
if(time.length() < 1){
valid = false;
lbltime.setForeground(Color.RED);
}
location = txtlocation.getText();
if(location.length() < 1){
valid = false;
lbllocation.setForeground(Color.RED);
}
details = txtdetails.getText();
if(details.length() < 1){
valid = false;
lbldetails.setForeground(Color.RED);
}
outcome = txtoutcome.getText();
if(outcome.length() < 1){
valid = false;
lbloutcome.setForeground(Color.RED);
}
did = txtdid.getText();
if(did.length() < 1){
valid = false;
lbldid.setForeground(Color.RED);
}
if(valid){
model.get(chosenRecord).setYourname(txtyourname.getText());
model.get(chosenRecord).setYourdepot(txtyourdepot.getText());
model.get(chosenRecord).setIncidentdate(txtdate.getText());
model.get(chosenRecord).setIncidenttime(txttime.getText());
model.get(chosenRecord).setLocation(txtlocation.getText());
model.get(chosenRecord).setDetails(txtdetails.getText());
model.get(chosenRecord).setOutcome(txtoutcome.getText());
model.get(chosenRecord).setDid(txtdid.getText());
}else{
// error(s) exist so don't try to construct Mat
mat = null;
lblError.setText("Errors in input - please correct.");
}
return valid;
}
}
private Model model = new Model(); // initialization is MISSING!
从EditDialog()
构造函数调用initGUI();
时,模型将保持null。
因此,的NPE
txtyourname.setText(model.get(0).getYourname()); // get(0) fails
您从未在Dialog类中初始化过您的模型
Model model = new Model();
此外,请尝试使您的代码sscce