以下程序用于从文本文件中输入整数并绘制XY图。我使用JFileChooser选择文件。我试图获取文件的完整路径。我为按钮创建了一个ActionListener方法。当我运行它时,我收到以下消息:
Exception in thread "main" java.lang.NullPointerException
at java.io.File.<init>(Unknown Source)
at pia.main(pia.java:34)
import java.awt.event.ActionEvent;
import java.awt.event.*;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import org.jfree.chart.*;
import org.jfree.chart.plot.*;
import org.jfree.data.xy.*;
public class Pio {
public static void main(String[] args) throws IOException {
JButton but = new JButton("Open file");
String URL = null;
but.addActionListener(new ActionListerner()
{
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
int ret = chooser.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
String URL = file.getPath();
}
});
File f = new File(URL);
FileReader inputF = new FileReader(f);
BufferedReader in = new BufferedReader(inputF);
int[] a = new int[100];
int[] b = new int[100];
String s = in.readLine();
int i = 0;
while (s != null && i < 100) { // your arrays can only hold 1000 ints
String pair[] = s.split(" ");
a[i] = Integer.parseInt(pair[0]);
b[i] = Integer.parseInt(pair[1]);
i++; // don't forget to increment
s = in.readLine();
}
in.close();
System.out.println("the output of the file is " + f);
XYSeries data = new XYSeries("Line Graph");
int n = a.length;
for (int j = 0; j < n; j++) {
data.add(a[j], b[j]);
}
XYDataset xY = new XYSeriesCollection(data);
JFreeChart chart = ChartFactory.createXYLineChart("line graph", "Cycles", "Temperature", xY, PlotOrientation.VERTICAL, true, true, true);
ChartFrame frame = new ChartFrame("Example", chart);
JPanel panel = new JPanel();
panel.add(but);
frame.add(panel);
frame.setSize(1000, 500);
frame.setVisible(true);
}
}
答案 0 :(得分:3)
定义一个类字段,使范围跨越整个类,如:
private String filePath;
// ...
public void actionPerformed(ActionEvent e)
{
JFileChooser chooser=new JFileChooser();
int ret = chooser.showDialog(null, "Open file");
if(ret == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
filePath = file.getPath();
}
}
现在,您可以像这样使用它:
if(filePath != null) System.out.println("The file path: " + filePath);
else System.out.println("The file path is not set yet!");
答案 1 :(得分:0)
您需要在String URL
范围之外声明ActionListener
。