我試圖運行腳本時遇到了NPE,我不明白爲什麼,目標是運行在我的JList中選擇的文件,因此這裏是代碼的相關位,開始我將JList的人羣:Java:JList getSelectedValue()NPE
File f1 = new File("ARForm.java");
String assetClasses = f1.getAbsolutePath();
String[] splits = assetClasses.split(":");
String pathName = splits[0] + ":\\";
File dir = new File(pathName);
String[] lista = dir.list();
@SuppressWarnings("unchecked")
JList list1 = new JList(lista);
JScrollPane js = new JScrollPane(list1);
這裏是類上市NPE,標線的一部分,這些代碼兩組來自兩個不同的班級。
Object fileName;
ARForm mform;
public void actionPerformed(ActionEvent a){
try{
**fileName = mform.list1.getSelectedValue();**
Process p = Runtime.getRuntime().exec(fileName.toString());
}
}
如果這還不夠,讓我知道和生病發布全班。 如果有更簡單的方法來做我所做的事情,請讓我知道。
編輯
這裏是我的班,我悟出了一些進口的是不必要的,因爲我懶了複製/粘貼:
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class Autorun extends JFrame{
public static void main(String[] args){
ARForm mform = new ARForm();
mform.setTitle("Security Roulette");
mform.pack();
mform.setLocationRelativeTo(null);
mform.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mform.setVisible(true);
}
}
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
public class ARForm extends JFrame{
JButton runButton;
JLabel lab;
File f1 = new File("ARForm.java");
String assetClasses = f1.getAbsolutePath();
String[] splits = assetClasses.split(":");
String pathName = splits[0] + ":\\";
File dir = new File(pathName);
String[] lista = dir.list();
@SuppressWarnings("unchecked")
JList list1 = new JList(lista);
JScrollPane js = new JScrollPane(list1);
public ARForm(){
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(1,2));
jp.add(js);
jp.add(runButton = new JButton("Run"));
runButton.setBounds(186, 10, 89, 23);
runButton.addActionListener(new ButtonAction());
add(jp);
}
}
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.io.*;
public class ButtonAction implements ActionListener{
Object fileName;
ARForm mform;
public void actionPerformed(ActionEvent a){
try{
fileName = mform.list1.getSelectedValue();
Process p = Runtime.getRuntime().exec(fileName.toString());
System.exit(0);
}
catch (IOException e){
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Yo Mama!");
}
}
}
你得到一個空指針異常的原因是因爲1-'mform'爲'null'或'mform.list1'爲'null'或者在執行'actionPerformed'時在列表中沒有被選中。 – MadProgrammer 2013-03-27 21:03:18
堆棧軌跡的頂部線條對我們來說很有幫助。 – MondKin 2013-03-27 21:57:48
線程「AWT-EventQueue-0」中的異常java.lang.NullPointerException \t at ButtonAction.actionPerformed(ButtonAction.java:12) – Lemiwinks 2013-03-27 23:53:52