doc = (StyledDocument) textPane.getDocument();
err = textPaneError.getStyledDocument();
try {
textPane.setText("\b");
doc.insertString(textPane.getCaretPosition(), (String) stack.pop(), styleT);
doc.insertString(textPane.getCaretPosition()-1, "\n", styleB);
} catch (BadLocationException e1) {
try {
err.insertString(0, "There is no opened tag", styleR);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
我正在尝试在JTextPane中打印所有异常。这是我的代码,它不起作用。有人能告诉我问题出在哪里? 感谢
答案 0 :(得分:0)
package printexception;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
public class PrintException extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new PrintException().setVisible(true); }
}
);
}
private final JTextPane text = new JTextPane();
public PrintException() {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setSize(400, 300);
initComponents();
}
private void initComponents() {
JToolBar toolbar = new JToolBar();
toolbar.add(new CreateException());
getContentPane().add(toolbar, BorderLayout.NORTH);
getContentPane().add(new JScrollPane(text));
}
private class CreateException extends AbstractAction {
CreateException() {
putValue(NAME, "Print Exception");
}
@Override
public void actionPerformed(ActionEvent evt) {
Exception ex = new Exception();
AttributeSet attr = null;
StyledDocument doc = text.getStyledDocument();
for (StackTraceElement trace : ex.getStackTrace()) {
try {
doc.insertString(doc.getLength(), trace.toString() + '\n', attr);
} catch (BadLocationException ex1) {
ex1.printStackTrace();
}
}
}
}
}