【发布时间】:2015-01-07 02:18:45
【问题描述】:
第一个问题:附加到特定行
我正在尝试使用getStyledDocumentmethod 附加到 JTextPane 中的特定行。例如:
try {
displayResults.getStyledDocument().insertString(5,"Hello",null);
} catch (BadLocationException ex) {
Logger.getLogger(ShapeData.class.getName()).log(Level.SEVERE, null, ex);
}
看来5 的偏移量只在水平方向上偏移了 5 个空格。除了insertString 之外,还有其他方法可以实现我想要做的事情吗?当我尝试从 excel 电子表格中向下输出行时,这也成为一个问题。我一直在诉诸于在我想要输出的特定字符串之前添加"\n"。
try {
displayResults.getStyledDocument().insertString(5,"\n + Hello",null);
} catch (BadLocationException ex) {
Logger.getLogger(ShapeData.class.getName()).log(Level.SEVERE, null, ex);
}
第二期:使用 HTML 代码附加下标
输入 excel 文件中的一些变量具有下标,因此我尝试使用 html 语法在 JTextPane 中输出它们。我已经尝试使用.setContentType("text/html") 方法两次。第一个是在获得styledDocument 之前。如果没有上面显示的 try-catch 语句,setContentType("text/html") 可以工作,但是一旦我尝试实现上面的 try-catch 语句,内容类型就会恢复为默认值。
我发现以下有关 stackoverflow 的问题很有帮助:
我尝试以这种方式使用上述链接中的解决方案:
HTMLDocument doc=(HTMLDocument) displayResults.getStyledDocument();
try {
doc.insertAfterEnd(doc.getCharacterElement(doc.getLength()),s1);
} catch (BadLocationException ex) {
Logger.getLogger(ShapeData.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ShapeData.class.getName()).log(Level.SEVERE, null, ex);
}
}
但是我不断收到一个错误提示:
Exception in thread "AWT-EventQueue-1" java.lang.ClassCastException: javax.swing.text.DefaultStyledDocument cannot be cast to javax.swing.text.html.HTMLDocument
我的完整代码
private void fullShapeTypesValueChanged(javax.swing.event.ListSelectionEvent evt) {
StoreData d = new StoreData(); // Class of data
SubstringGenerator gen = new SubstringGenerator();
labels = d.getLabels(); // Get the headers of each excel column
for (int i = 76; i >= 0 ; i--){
int character = 0; // variable to help determine the number of characters of the label
String s1 = "";
String s2 = "";
String s3 = "";
character = labels[i].length();
/* Any characters after the first one
* will be converted to subscript using HTML.
* second variable in gen.subscriptGen(a, b) --> "b" will be converted to
* <html><sub>b</sub></html>
*/
switch(character){
case 1:
s2 = labels[i];
s1 = s2;
break;
case 2:
case 3:
case 4:
case 5:
s3 = gen.subscriptGen(s2, labels[i].substring(1));
s1 = s3;
break;
}
HTMLDocument doc=(HTMLDocument) displayResults.getStyledDocument();
try {
doc.insertAfterEnd(doc.getCharacterElement(doc.getLength()),s1);
} catch (BadLocationException ex) {
Logger.getLogger(ShapeData.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ShapeData.class.getName()).log(Level.SEVERE, null, ex);
}
}
displayResults.setContentType("text/html");
}
【问题讨论】: