你不应该创建一个新JTextPane
每次你JButton
被点击了。通过setText:
你永远不通过setText:
CSV文件的内容设置为您JTextPane
到JFrame
并在ActionListener
刚刚设置的值,一旦添加窗格,但你只能通过它打印出来System.out.println("Student - " + grades[0] + " "+ grades[1] + " Grade - " + grades[2]);
这里我给你举了一个例子。这个例子并不是真的基于你的发布代码,因为它会花费很多精力来查看你的整个代码并纠正它,但它显示了你为了使代码工作所需做的一切。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Instructor {
public static void main(String[] args) {
JFrame frame = new JFrame("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setLayout(new BorderLayout());
final JTextPane textPane;
textPane = new JTextPane();
frame.add(textPane,BorderLayout.CENTER);
JButton button = new JButton("Read CSV");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Reset textpanes content so on every button click the new content of the read file will be displayed
textPane.setText("");
String fileResult = "";
try {
BufferedReader csvReader = new BufferedReader(new FileReader("myCSV.csv"));
String line = null;
while ((line = csvReader.readLine()) != null) {
//Do your logic here which information you want to parse from the csv file and which information you want to display in your textpane
fileResult = fileResult + "\n" +line;
}
}
catch(FileNotFoundException ex) {
System.err.println("File was not found");
}
catch(IOException ioe) {
System.err.println("There was an error while reading the file");
}
textPane.setText(fileResult);
}
});
frame.add(button,BorderLayout.SOUTH);
frame.setVisible(true);
}
}
所以我做了什么:
- 创建
JTextpane
不在ActionListener
但一旦
- 读取文件中的
ActionListener
,为了提供try
和catch
,以确保有一定的误差处理文件无法找到或类似的东西。
- 不要通过
System.out.println();
打印csv的结果,但通过调用setText:
方法将结果设置为JTextPane
。
我还添加了LayoutManger
(BorderLayout
)代替添加JTextPane
和按钮到JFrame
与NullLayout
。这不是问题的一部分,但如果你有时间,应该改变它,因为根本不推荐使用NullLayout
(代码中的setBounds
)。
好吧,我想我已经得到你说的第一部分,并已纠正这一点。至于第二部分,你是什么意思?我如何着手将csv文件的内容设置为JTextPane? –
我会在一分钟内给你一个例子 – dehlen
我非常感谢你的帮助。我在这个班上苦苦挣扎,很难找到帮助。 –