【问题标题】:File writing issues - file is blank文件写入问题 - 文件为空白
【发布时间】:2015-08-10 23:56:39
【问题描述】:
import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import java.awt.CardLayout;
import javax.swing.JSplitPane;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.awt.event.ActionEvent;
import javax.swing.JEditorPane;
import java.awt.Color;
import java.awt.Font;
import javax.swing.DropMode;
import javax.swing.JScrollBar;
import javax.swing.SwingConstants;

public class Program extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private JTextField textField_1;

    /**
     * Launch the application.
     */

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Program frame = new Program();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * Create the frame.
     *
     * @throws BadLocationException
     */
    public Program() throws BadLocationException {
        double points = 0;
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(0, 0, 1200, 760);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JEditorPane dtrpnTypeTextHere = new JEditorPane();
        dtrpnTypeTextHere.setContentType("type/normal");
        dtrpnTypeTextHere.setToolTipText("");
        dtrpnTypeTextHere.setFont(new Font("Arial", Font.PLAIN, 16));
        dtrpnTypeTextHere.setForeground(Color.GREEN);
        dtrpnTypeTextHere.setBackground(Color.BLACK);
        dtrpnTypeTextHere.setBounds(10, 23, 1152, 671);
        contentPane.add(dtrpnTypeTextHere);
        int length = dtrpnTypeTextHere.getDocument().getLength();
        String text = dtrpnTypeTextHere.getDocument().getText(0, length);
        JLabel lblNewLabel = new JLabel("Power Text Editor");
        lblNewLabel.setBackground(Color.BLACK);
        lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
        lblNewLabel.setForeground(Color.GREEN);
        lblNewLabel.setBounds(515, 0, 125, 14);
        contentPane.add(lblNewLabel);
        JLabel lblFileName = new JLabel("File Name:");
        lblFileName.setBounds(660, 703, 75, 14);
        contentPane.add(lblFileName);
        JButton btnFinishEditing = new JButton("Finish editing");
        btnFinishEditing.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                BufferedWriter writer = null;
                try {
                    //create a temporary file
                    File logFile = new File("yas.txt");

                    // This will output the full path where the file will be written to...
                    System.out.println(logFile.getCanonicalPath());
                    writer = new BufferedWriter(new FileWriter(logFile));
                    writer.write(text);
                } catch (Exception e1) {
                    e1.printStackTrace();
                } finally {
                    try {
                        // Close the writer regardless of what happens...
                        writer.close();
                    } catch (Exception e1) {
                    }

                    System.out.println("Quit because of user exit");
                    System.exit(0);

                }
            }
        });
        btnFinishEditing.setForeground(Color.GREEN);
        btnFinishEditing.setBackground(Color.BLACK);
        btnFinishEditing.setBounds(532, 699, 108, 23);
        contentPane.add(btnFinishEditing);

        textField_1 = new JTextField();
        textField_1.setBounds(726, 700, 131, 20);
        contentPane.add(textField_1);
        textField_1.setColumns(10);

    }
}

有代码,我在制作文件时遇到问题,当我输入内容时,它在文件中显示为空白。

【问题讨论】:

  • contentPane.setLayout(null); Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上使用不同语言环境中的不同 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。

标签: java swing file file-io io


【解决方案1】:

您在事件驱动的环境中操作,这意味着在创建组件和显示 UI 和发生某些事情之间,时间已经过去了。

这意味着当你做类似...

        JEditorPane dtrpnTypeTextHere = new JEditorPane();
        dtrpnTypeTextHere.setContentType("type/normal");
        dtrpnTypeTextHere.setToolTipText("");
        dtrpnTypeTextHere.setFont(new Font("Arial", Font.PLAIN, 16));
        dtrpnTypeTextHere.setForeground(Color.GREEN);
        dtrpnTypeTextHere.setBackground(Color.BLACK);
        dtrpnTypeTextHere.setBounds(10, 23, 1152, 671);
        contentPane.add(dtrpnTypeTextHere);
        int length = dtrpnTypeTextHere.getDocument().getLength();
        String text = dtrpnTypeTextHere.getDocument().getText(0, length);

然后类似...

btnFinishEditing.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        BufferedWriter writer = null;
        try {
            //create a temporary file
            File logFile = new File("yas.txt");

            // This will output the full path where the file will be written to...
            System.out.println(logFile.getCanonicalPath());
            writer = new BufferedWriter(new FileWriter(logFile));
            writer.write(text);
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            try {
                // Close the writer regardless of what happens...
                writer.close();
            } catch (Exception e1) {
            }

            System.out.println("Quit because of user exit");
            System.exit(0);

        }
    }
});

发生了,text 的值不会改变,但JEditorPane 的内容会改变。您分配给text 的值与JEditorPane 的内容之间根本没有关系,除非您执行此操作的时间。

所以,不要这样做......

int length = dtrpnTypeTextHere.getDocument().getLength();
String text = dtrpnTypeTextHere.getDocument().getText(0, length);

在构造函数中,你应该在ActionListener...

btnFinishEditing.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        int length = dtrpnTypeTextHere.getDocument().getLength();
        String text = dtrpnTypeTextHere.getDocument().getText(0, length);
        BufferedWriter writer = null;
        try {
            //create a temporary file
            File logFile = new File("yas.txt");

            // This will output the full path where the file will be written to...
            System.out.println(logFile.getCanonicalPath());
            writer = new BufferedWriter(new FileWriter(logFile));
            writer.write(text);
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            try {
                // Close the writer regardless of what happens...
                writer.close();
            } catch (Exception e1) {
            }

            System.out.println("Quit because of user exit");
            System.exit(0);

        }
    }
});

举个例子。

您可能还想看看The try-with-resources Statement,这将降低您的文件写入try-catch-finally 块的复杂性;)

作为旁注,避免使用null 布局,像素完美布局是现代 UI 设计中的一种错觉。影响组件单个尺寸的因素太多,您无法控制。 Swing 旨在与核心的布局管理器一起工作,丢弃这些将导致无穷无尽的问题和问题,您将花费越来越多的时间来尝试纠正

【讨论】:

    【解决方案2】:

    您的方法 Program 在程序开始时运行一次以设置 UI。您在程序运行时声明和设置变量文本。鉴于在初始化程序时没有输入任何文本,您的文件中总是会得到一个空字符串。

    你需要做的是将变量文本和读取文本的代码从JEditorPane dtrpnTypeTextHere移动到动作的开头。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多