如何为在JTextPane

时间:2017-04-06 13:16:48

标签: java swing utf-8 jframe jtextpane

我有一个单独的类JFrame,当用户点击主框架上的按钮时会打开。该框架有一个显示内容的JTextPane。我用下面写的代码打开我的文件。但在斯洛文尼亚,我们有一些没有正确显示的字母(例如烤鸡=piščanecnažaru......其中š,č和ž显示为正方形)。

我的问题是,是否可以在不更改字体的情况下为文本或文件设置UTF-8编码?字体必须保持默认值(使用NetBeans)。

public class EditFrame extends javax.swing.JFrame {

    public void readFile(File f) {
        try {
            textPane.read(new java.io.FileReader(f), null);
        } catch (IOException ex) {
            Logger.getLogger(EditFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    ...
}

1 个答案:

答案 0 :(得分:2)

您必须指定要读取的文件的编码。

可以这样做:

BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
textPane.read(reader, null);