2015-04-19 175 views
0

OK所以我正在爲類做一個項目,並且我已經得到了我需要的工作(現在)。我現在想要做的是當我單擊它顯示文本窗格中的所有數據。到目前爲止,它所做的只是打印Grades(我明白爲什麼)但我希望它能打印出CSV文件中正在分析的內容。我並沒有要求任何人魔法般地解決我的大部分代碼,我只是不知道如何讓按鈕實際顯示所需的結果,這讓我很生氣,因爲我終於得到了代碼來做什麼我想要但我看不到結果。 (它在控制檯中工作,但在運行.jar時不顯示任何內容。)如何將CSV文件讀取到文本窗格Java

已回答問題請閱讀下面的註釋。代碼已被刪除。感謝您的時間!

回答

0
  1. 你不應該創建一個新JTextPane每次你JButton被點擊了。通過setText:

  2. 你永遠不通過setText: CSV文件的內容設置爲您JTextPaneJFrame並在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); 
    } 

} 

所以我做了什麼:

  1. 創建JTextpane不在ActionListener但一旦
  2. 讀取文件中的ActionListener,爲了提供trycatch,以確保有一定的誤差處理文件無法找到或類似的東西。
  3. 不要通過System.out.println();打印csv的結果,但通過調用setText:方法將結果設置爲JTextPane

我還添加了LayoutMangerBorderLayout)代替添加JTextPane和按鈕到JFrameNullLayout。這不是問題的一部分,但如果你有時間,應該改變它,因爲根本不推薦使用NullLayout(代碼中的setBounds)。

+0

好吧,我想我已經得到你說的第一部分,並已糾正這一點。至於第二部分,你是什麼意思?我如何着手將csv文件的內容設置爲JTextPane? –

+0

我會在一分鐘內給你一個例子 – dehlen

+0

我非常感謝你的幫助。我在這個班上苦苦掙扎,很難找到幫助。 –