【问题标题】:How would I fix this JTextArea formatting error?我将如何解决这个 JTextArea 格式错误?
【发布时间】:2016-12-01 11:11:15
【问题描述】:

我正在开发一个简单的文件阅读器。它读取 .txt 文件,然后格式化输出并将输出显示在 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

电流输出:

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

【问题讨论】:

  • 要么不打印全名,要么使用另一个标签
  • 您必须根据要打印的字符串的长度来设置要打印的制表符 (\t) 的数量。
  • 您的预期输出是什么?对齐问题是问题吗?
  • 感谢您的帮助。问题是对齐,抱歉没有指定;我已经添加了预期的输出。
  • 我已经编辑了这个问题。现在,控制台中的输出很好,但在 JTextArea 中却不行。

标签: java swing file text jtextarea


【解决方案1】:

现在,控制台中的输出正常,但在 JTextArea 中却不行。

如果您希望文本像在控制台上一样对齐,则需要使用等宽字体

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

您可能还需要使用:

textArea.setTabSize(...);

【讨论】:

    猜你喜欢
    • 2020-11-04
    • 1970-01-01
    • 2016-07-21
    • 2016-09-09
    • 1970-01-01
    • 2015-02-28
    相关资源
    最近更新 更多