2016-12-01 57 views
0

我正在研究一个简单的文件阅读器。它读取.txt文件,然后格式化输出并在JTextArea中显示输出。出于某种原因,输出无法正确显示。我已经给出了我的当前代码,后面跟着下面的文本文件内容。我该如何解决这个JTextArea格式错误?

代码

public static JTextArea display = new JTextArea(); 

public static void main(String[] args) { 

     // GUI 

     JFrame frame = new JFrame("Haberdasher"); 
     frame.setSize(450, 300); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setLocationRelativeTo(null); 

     JPanel container = new JPanel(); 
     container.setLayout(null); 
     frame.setContentPane(container); 

     JScrollPane scroll = new JScrollPane(display); 
     scroll.setBounds(10, 10, 415, 150); 

     container.add(scroll); 

     frame.toFront(); 
     frame.setVisible(true); 


     // Logic 


     String path = "src//employees.txt"; 

     boolean endOfFile = false; 

     String output = "Name" + "\t\t" + "Weekly Sales" + "\t\t" + "Weekly Pay" + "\n"; 

     try { 
      FileReader fr = new FileReader(path); 
      BufferedReader br = new BufferedReader(fr); 

      while (!endOfFile) { 

       String name = br.readLine(); 

       if(name == null) { 
        endOfFile = true; 
       } else { 
        int sale = Integer.parseInt(br.readLine()); 

        if(name.length() >= 16) { 
         output += name + "\t" + sale + "\t\t" + "300" + "\n"; 
        } else { 
         output += name + "\t\t" + sale + "\t\t" + "300" + "\n"; 
        } 
       } 
      } 
      br.close(); 
      System.out.println(output); 
      display.setText(output); 
     } catch (IOException e) { 
      System.out.println(e); 
     } 
    } 

employees.txt内容:http://hastebin.com/ijuyedizil.nginx

电流输出:enter image description here

预期输出:http://hastebin.com/epesipatot.nginx

+0

要么不打印整个名称或使用其他选项卡 –

+0

您必须根据要打印的字符串的长度来制作打印的标签数量(\ t)。 –

+0

您的预期产出是多少?这种对齐问题是否是问题? – Coder

回答

1

现在,输出在控制台中很好,但不在JTextArea中。

如果你想要的文字对齐像它的控制台需要使用等宽字体

textArea.setFone(new Font("monospaced", Font.PLAIN, 10)); 

你也可能需要使用:

textArea.setTabSize(...); 
相关问题