下面的代码用于创建折线图。我能够在 TextArea 中显示整数,但我无法在文本文件中显示整数上方的句子。我该如何纠正这个程序?
文本文件的屏幕截图如下所示。
我希望文本文件的前三行也打印在 TextArea 中。
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import org.jfree.chart.*;
import org.jfree.chart.plot.*;
import org.jfree.data.xy.*;
public class Pio {
static JFrame frame1 = new JFrame("Graph");
static String URL = null;
static JTextArea txt = new JTextArea();
static JPanel panel = new JPanel();
public static void main(String[] args) throws IOException {
JButton but = new JButton("Open file");
![enter image description here][2]
panel.add(but);
frame1.add(panel, BorderLayout.WEST);
frame1.setVisible(true);
frame1.setSize(1000,400);
but.addActionListener(new ActionListener()
{
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();
URL = file.getAbsolutePath();
}
File f = new File(URL);
FileReader inputF = null;
try {
inputF = new FileReader(f);
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
BufferedReader in = new BufferedReader(inputF);
int[] a = new int[100];
int[] b = new int[100];
String s=null;
try {
s = in.readLine();
}
catch (IOException e1) {
e1.printStackTrace();
}
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
try {
s = in.readLine();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
try {
in.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
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);
ChartPanel p=new ChartPanel(chart);
p.setVisible(true);
p.setLocation(100,100);
p.setSize(500,500);
frame1.add(p,BorderLayout.EAST);
}
});
}
}