我在尝试运行我的脚本时遇到了 NPE,但我不明白为什么,目标是运行在我的 JList 中选择的文件,所以这里是相关的代码位,从我的 JList 人口开始:
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!");
}
}
}