我有一个格式良好的文本文件,如下所示:
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)));
}
最佳答案
您将调用 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();
}
});
}
}
关于java - 在 TextArea 中输入并格式化文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29243273/