1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| package fr.sca.tests.HTMLEditorPaneTest;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.StringWriter;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
/**
* Hello world!
*
*/
public class App {
private JEditorPane ePane;
private JEditorPane emptyEPane;
private HTMLEditorKit kit = new HTMLEditorKit();
private HTMLEditorKit emptyKit = new HTMLEditorKit();
private String htmlContent="<html><head></head><body>blabla<br><font color=\"#FFCC66\"><b>foobar</b></font><br>blabla</body></html>";
public App() {
ePane = new JEditorPane();
//ePane.setEditorKit(new HTMLEditorKit());
ePane.setEditable(false);
ePane.setEditorKit(kit);
ePane.setContentType("text/html");
ePane.setText(htmlContent);
emptyEPane = new JEditorPane();
emptyEPane.setEditorKit(emptyKit);
emptyEPane.setDocument(new HTMLDocument());
emptyEPane.setEditable(false);
emptyEPane.setContentType("text/html");
JButton copyButton = new JButton("Copy");
copyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(ePane.getSelectedText());
System.out.println(ePane.getText());
StringWriter writer = new StringWriter();
try {
kit.write(writer, ePane.getDocument(), ePane.getSelectionStart(), ePane.getSelectedText().length());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(writer.toString());
try {
HTMLDocument doc = (HTMLDocument) emptyEPane.getDocument();
kit.insertHTML(doc, 0, writer.toString(), 0, 0, null);
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
JFrame f = new JFrame();
f.add(ePane);
f.add(emptyEPane,BorderLayout.EAST);
f.add(copyButton,BorderLayout.WEST);
f.setSize(800, 600);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
new App();
}
} |
Partager