Hi Eric,
Here is a sample code. When user enters [ENTER] key, you will see the behavior is correct although you will get a pair of <p></p> tags. This is the way I do it. The problem is that when you want to display saved html in JTextPane next time, you have to replace all <br> tags to <p></p> tags. I am not sure if this will help you or not. As I said before this is the way I solved the problem before deadline and you may overwrite [ENTER] key or add [SHIFT][ENTER] to yourTextPane's keymap. Good luck to you.
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
public class
test extends JFrame {
private StyleSheet css = new StyleSheet();
private JEditorPane editor = new JEditorPane();
private HTMLEditorKit kit = new HTMLEditorKit();
private HTMLDocument
doc = new HTMLDocument();
private JButton showSource = new JButton("Show Source");
public test() {
css.addRule("BODY{ margin : 0;}");
kit.setStyleSheet(css);
editor.setDocument(doc);
editor.setEditorKit(kit);
editor.setBorder(null);
editor.setEditable(true);
JScrollPane scroll = new JScrollPane(editor);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(scroll, BorderLayout.CENTER);
this.getContentPane().add(showSource, BorderLayout.SOUTH);
this.showSource.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("Original html:");
System.out.println(editor.getText());
System.out.println("After you take care of <p></p>");
System.out.println(takeCareOfPTag(editor.getText()));
}
});
setSize(220, 180);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public
String takeCareOfPTag (String origHtmlString) {
if (origHtmlString == null) return null;
//Step 1:RemoveAll invisible characters which ASII value is less than 32
StringBuffer sb = new StringBuffer(origHtmlString);
for (int i = sb.length()-1; i >=0; i--) {
char aChar = sb.charAt(i);
if (((int)aChar) < 32)
sb.deleteCharAt(i);
}
//Step 2
elete all <P> or <p>
int index5 = sb.lastIndexOf("<P>");
while (index5 >= 0) {
sb.delete(index5, index5+ 3);
index5 = sb.lastIndexOf("<P>");
}
int index6 = sb.lastIndexOf("<p>");
while (index6 >= 0) {
sb.delete(index6, index6+3);
index6 = sb.lastIndexOf("<p>");
}
//Step 3:Replace all </p> by <br> and take care of white space
origHtmlString = sb.toString();
if (origHtmlString.indexOf("/p>") >0) {
String[] qTextString = origHtmlString.split("</p>");
if (qTextString != null) {
origHtmlString = qTextString[0].trim();
if (qTextString.length > 1) {
for (int i = 1; i < qTextString.length; i ++) {
origHtmlString = origHtmlString + "<br>" + qTextString[i].trim();
}
}
}
}
return origHtmlString;
}
public static void main(String[] args) {
new test().setVisible(true);
}
}
Renee