【问题标题】:Java Swing send text from JTextArea to txt file on separate linesJava Swing 将文本从 JTextArea 发送到单独的行上的 txt 文件
【发布时间】:2018-01-17 00:18:16
【问题描述】:

我有一个JTextArea

当我将此数据写入文本文件时,它会全部打印在同一行:

如何使文本文件的输出与文本区域中的输出相同,分两行?

文本区域的代码,将数据写入文本。

JTextArea matrixArea = new JTextArea();
matrixArea.setBounds(139, 63, 337, 111);
dataPanel.add(matrixArea);

JButton sendData = new JButton("Send Data");
sendData.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        String nrPatterns = patternText.getText().toString();
        String inputTex = inputText.getText().toString();
        String otputTex = outputText.getText().toString();
        String matrixW  = matrixArea.getText().toString();

        try {
            FileWriter writer = new FileWriter("test.txt", true);
            writer.write(nrPatterns);
            writer.write(" ");
            writer.write(inputTex);
            writer.write(" ");
            writer.write(otputTex);
            writer.write(" ");
            writer.write(System.getProperty("line.separator"));
            writer.write(matrixW);
            writer.close();
            JOptionPane.showMessageDialog(window, "Success");
        }catch(Exception e){
            JOptionPane.showMessageDialog(window, "Error", "Error",  JOptionPane.ERROR_MESSAGE);
        }
    }
});

【问题讨论】:

  • split("\n") 不起作用?
  • 啊,记事本,你在...代码中感到痛苦。记事本在打印行之前需要\n(新行)和\r(返回)。您可以尝试将文件加载到其他编辑器或使用System.lineSeparator 并用它替换Strings 中的所有\n 字符......作为头顶的一些想法 - For more info
  • 试过了,没用:(
  • 1) 见JTextComponent.write(java.io.Writer) 2) matrixArea.setBounds(139, 63, 337, 111); Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同的语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或combinations of them 以及white space 的布局填充和边框。 ..
  • .. 使用 rows/cols 建议此文本区域的大小,并使用布局约束进行定位。 3) “尝试过,没有帮助” 提示:添加@MadProgrammer(或任何重要的@)以通知新评论的人。 4) 为了尽快获得更好的帮助,请发帖minimal reproducible exampleShort, Self Contained, Correct Example

标签: java swing jtextarea


【解决方案1】:

在你最后一个 .write 之后使用这个:

writer.newLine();

【讨论】:

  • 你需要使用 BufferedWriter 来使用 newline() 方法。
  • 你说得对!所以改变你的 FileWriter,这就是我所希望的
猜你喜欢
  • 1970-01-01
  • 2012-04-16
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 2011-09-15
  • 1970-01-01
  • 2019-10-23
  • 2011-11-30
相关资源
最近更新 更多