你不應該創建一個新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
我非常感謝你的幫助。我在這個班上苦苦掙扎,很難找到幫助。 –