2015-03-24 86 views
0

一個格式化的文本文件,我有一個很好格式化文本文件,它看起來像這樣:輸入TextArea中

Human 10000 
Alien 2000 
Dog 40000 

我如何可以插入在JTextArea中這段文字不破壞格式?

我試圖用我用的文件相同的格式,但它不工作:

String formatStr = "%-15s %-15s"; 
while((currentLine = br.readLine()) != null) { 
    area.setText(area.getText() + "\n" + c++ + "."); 
    area.setText(String.format(formatStr, area.getText(), String.valueOf(currentLine))); 
} 

回答

6

你會打電話的JTextArea的append(...)方法,而不是setText(...),如果你想在你的循環追加多行,將字體設置爲Font.MONOSPACED,並且可能會使用String.format(...),這比標籤更可靠和靈活。但我自己,我會使用JTable來顯示錶格數據。

我的意思是這樣......

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 

import javax.swing.*; 
import javax.swing.table.DefaultTableModel; 

public class TabularData extends JPanel { 
    private static final String FILE_NAME = "dataFile.txt"; // **** this is wrong **** 
    private static final String[] COLUMN_NAMES = {"Species", "Count"}; 
    private static final String REGEX = "\\s+"; 
    private MyModel myModel = new MyModel(); 
    private JTable table = new JTable(myModel); 

    public TabularData() { 
     add(new JScrollPane(table)); 

     File dataFile = new File(FILE_NAME); 
     try(BufferedReader br = new BufferedReader(new FileReader(dataFile))) { 
     String currentLine = ""; 
     while ((currentLine = br.readLine()) != null) { 
      String[] tokens = currentLine.split(REGEX); 
      if (tokens.length == 2) { 
       String species = tokens[0].trim(); 
       int count = Integer.parseInt(tokens[1].trim()); 
       myModel.addRow(new Object[]{species, count}); 
      } 
     } 
     } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
     } catch (IOException e) { 
     e.printStackTrace(); 
     } catch (NumberFormatException e) { 
     e.printStackTrace(); 
     } 
    } 

    private class MyModel extends DefaultTableModel { 

     public MyModel() { 
     super(COLUMN_NAMES, 0); 
     } 

     @Override 
     public Class<?> getColumnClass(int columnIndex) { 
     if (getRowCount() > 0) { 
      Object cell = getValueAt(0, columnIndex); 
      if (cell != null) { 
       return cell.getClass(); 
      } 
     } 
     return super.getColumnClass(columnIndex); 
     } 
    } 

    private static void createAndShowGui() { 
     JFrame frame = new JFrame("TabularData"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(new TabularData()); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 
+0

你的意思是這樣嗎? :「area.append(C++ +」。「+ currentLine +」\ n「);」 – zaa 2015-03-24 21:38:12

+0

@zaa:沒有更像編輯的東西 – 2015-03-24 21:52:23

+0

謝謝!我會用這個:) – zaa 2015-03-24 22:20:54