2015-04-19 163 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

我非常感谢你的帮助。我在这个班上苦苦挣扎,很难找到帮助。 –