Перезагрузить панель редактора

Я нашел здесь: что я искал, но все же у меня есть некоторые проблемы.

Это мой код действия:

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) throws IOException {

    jEditorPane1.setContentType("text/html");


    int returnVal = FileChooser1.showOpenDialog(this);
    if (returnVal == FileChooser1.APPROVE_OPTION) {


String image = String.format("<img src=\"%s\">", FileChooser1.getSelectedFile());
    jEditorPane1.setText(image);

    }
}

Вот скриншот того, что происходит, как вы можете видеть, изображение не загружается. http://postimg.org/image/agc665ih1/

Но если я сохраню файл (с помощью кнопки «Сохранить») и снова открою тот же файл (с помощью кнопки «Открыть»), изображение будет там и отлично загружено.

Я уже пробовал методы .repaint() и .revalidate(), но они не работают. Есть идеи?


person DJack    schedule 12.08.2013    source источник


Ответы (3)


Это может быть проблемой при настройке пути на странице JEditorPane. использовать это:

String image = String.format("<img src=\"%s\">", FileChooser1.getSelectedFile().getPath());

Я предполагаю, что вы уже выбрали соответствующий editorKit для JEditorPane.

person Ashwani    schedule 12.08.2013
comment
Нет, я получаю тот же результат:/ Для JEditorPane я выбрал HTMLeditorKit(), код выглядит так: jEditorPane1.setEditorKit(new HTMLEditorKit()); - person DJack; 12.08.2013
comment
Я думаю, что это не проблема, но я вставлю код, как только смогу ответить на свой вопрос, потому что мне приходится ждать несколько часов из-за моей репутации.. :) - person DJack; 12.08.2013

Итак, теперь я могу ответить своим кодом. Я использую этот класс для выбора файла:

import java.io.File;

импортировать javax.swing.filechooser.FileFilter;

класс jpgfilter расширяет FileFilter {

    public boolean accept(File file) {
        return file.isDirectory() || file.getAbsolutePath().endsWith(".jpg");
    }

    public String getDescription() {

        return "JPG image (*.jpg)";
    }

}

И в моем основном классе у меня есть это:

FileChooser1 = new javax.swing.JFileChooser();
    FileChooser1.setDialogTitle("Choose your image:");
    FileChooser1.setFileFilter(new jpgfilter());

Вот и все.

person DJack    schedule 13.08.2013

Итак, я действительно нашел какое-то решение, но я думаю, что кода действительно слишком много, и что я должен сделать это легко. На самом деле я вставляю изображение и одновременно сохраняю и открываю содержимое EditorPane как файл .html.

Код:

    jEditorPane1.setContentType("text/html");

    int returnVal = FileChooser1.showOpenDialog(this);
    if (returnVal == FileChooser1.APPROVE_OPTION) {

        String image = String.format("<img src=\"%s\">", FileChooser1
                .getSelectedFile().getPath());

        jEditorPane1.setText(image);

        String type = jEditorPane1.getContentType();

        OutputStream os = new BufferedOutputStream(new FileOutputStream(
                "/Library/java_test/temp" + ".html"));

        Document doc = jEditorPane1.getDocument();
        int length = doc.getLength();

        if (type.endsWith("/rtf")) {
            // Saving RTF - use the OutputStream
            try {
                jEditorPane1.getEditorKit().write(os, doc, 0, length);
                os.close();
            } catch (BadLocationException ex) {
            }
        } else {
            // Not RTF - use a Writer.
            Writer w = new OutputStreamWriter(os);
            jEditorPane1.write(w);
            w.close();
        }

        String url = "file:///" + "/Library/java_test/temp" + ".html";

        jEditorPane1.setPage(url);

    }
person DJack    schedule 13.08.2013