下面列出了javax.swing.text.StyledDocument#insertString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void testCallingFromAWTIsOk() throws Exception {
StyledDocument doc = support.openDocument();
doc.insertString(0, "Ble", null);
assertTrue("Modified", support.isModified());
class AWT implements Runnable {
boolean success;
public synchronized void run() {
success = support.canClose();
}
}
AWT b = new AWT();
javax.swing.SwingUtilities.invokeAndWait(b);
assertTrue("Ok, we managed to ask the question", b.success);
if (ErrManager.messages.length() > 0) {
fail("No messages should be reported: " + ErrManager.messages);
}
}
private void processTest(String testName, String insertionText) throws Exception {
File testFile = new File(getDataDir(), testName);
FileObject testObject = FileUtil.createData(testFile);
DataObject dataObj = DataObject.find(testObject);
EditorCookie.Observable ed = dataObj.getCookie(Observable.class);
handler.params.clear();
handler.latest = null;
StyledDocument doc = ed.openDocument();
ed.open();
Thread.sleep(TIMEOUT);
handler.params.clear();
for (int i = 0; i < ITERATIONS_COUNT; i++) {
doc.insertString(0, insertionText, null);
Thread.sleep(TIMEOUT);
}
for (int i = 0; i < ITERATIONS_COUNT; i++) {
doc.remove(0, insertionText.length());
Thread.sleep(TIMEOUT);
}
ed.saveDocument();
ed.close();
assertClean();
}
public static void appendIconAndText(JTextPane textPane, Image image, String message) {
StyledDocument document = (StyledDocument)textPane.getDocument();
image = StatusMessageImageConverter.convertImage(image);
try {
JLabel jl = JLabelFactory.createJLabel("<html>" + message + "</html>", image);
jl.setHorizontalAlignment(SwingConstants.LEFT);
String styleName = "style"+message;
Style textStyle = document.addStyle(styleName, null);
StyleConstants.setComponent(textStyle, jl);
document.insertString(document.getLength(), " ", document.getStyle(styleName));
} catch (BadLocationException e) {
throw new IllegalStateException(e);
}
}
public static void appendTextUsingLabel(JTextPane textPane, String message) {
StyledDocument document = (StyledDocument)textPane.getDocument();
try {
JLabel jl = JLabelFactory.createJLabel(message);
jl.setHorizontalAlignment(SwingConstants.LEFT);
String styleName = "style"+message;
Style textStyle = document.addStyle(styleName, null);
StyleConstants.setComponent(textStyle, jl);
document.insertString(document.getLength(), " ", document.getStyle(styleName));
} catch (BadLocationException e) {
throw new IllegalStateException(e);
}
}
public static void appendIcon(JTextPane textPane, Image image) {
StyledDocument document = (StyledDocument)textPane.getDocument();
image = StatusMessageImageConverter.convertImage(image);
try {
JLabel jl = JLabelFactory.createJLabel(image);
jl.setHorizontalAlignment(SwingConstants.LEFT);
String styleName = "style"+image.toString();
Style textStyle = document.addStyle(styleName, null);
StyleConstants.setComponent(textStyle, jl);
document.insertString(document.getLength(), " ", document.getStyle(styleName));
} catch (BadLocationException e) {
throw new IllegalStateException(e);
}
}
public void testCheckCSS() throws Exception{
final String err1 = "\nNEW {";
final String err2 = "{font-size: 12px; \n _color:black}";
Node node = WebPagesNode.getInstance(projectName).getChild(cssFileName, Node.class);
StyledDocument doc = openFile(projectName, cssFileName);
checkCSS(node);
doc.insertString(doc.getLength()-1, err1, null);
checkCSS(node);
doc.insertString(doc.getLength()-1, err2, null);
checkCSS(node);
int errPos = doc.getText(0, doc.getLength()).indexOf("{{");
doc.remove(errPos, 1);
checkCSS(node);
errPos = doc.getText(0, doc.getLength()).indexOf("_");
doc.remove(errPos, 1);
checkCSS(node);
ending();
}
public void actionPerformed(ActionEvent ae) {
JTextComponent tComp = (JTextComponent) ae.getSource();
if (tComp.getDocument() instanceof StyledDocument) {
doc = (StyledDocument) tComp.getDocument();
try {
doc.getText(0, doc.getLength(), segment);
}
catch (Exception e) {
// should NEVER reach here
e.printStackTrace();
}
int offset = tComp.getCaretPosition();
int index = findTabLocation(offset);
buffer.delete(0, buffer.length());
buffer.append('\n');
if (index > -1) {
for (int i = 0; i < index + 4; i++) {
buffer.append(' ');
}
}
try {
doc.insertString(offset, buffer.toString(),
doc.getDefaultRootElement().getAttributes());
}
catch (BadLocationException ble) {
ble.printStackTrace();
}
}
}
public void testOpenJSP() throws Exception {
StyledDocument doc = prepare("performance.jsp");
doc.insertString(0, "${\"hello\"}", null);
waitTimeout();
doc.insertString(doc.getEndPosition().getOffset() - 1, "<%= \"hello\" %>", null);
waitTimeout();
for (LogRecord log : timerHandler.logs) {
if (log.getMessage().contains("Navigator Initialization")) {
verify(log, 500, 2000);
} else {
verify(log, 200, 800);
}
}
}
private void insertColonyButtons(StyledDocument doc, List<Colony> colonies) throws Exception {
for (Colony colony : colonies) {
StyleConstants.setComponent(doc.getStyle("button"), createColonyButton(colony, false));
doc.insertString(doc.getLength(), " ", doc.getStyle("button"));
doc.insertString(doc.getLength(), ", ", doc.getStyle("regular"));
}
doc.remove(doc.getLength() - 2, 2);
}
public void notifyStatusUpdate(String pMessage) {
try {
StyledDocument doc = jTextPane1.getStyledDocument();
doc.insertString(doc.getLength(), "(" + dateFormat.format(new Date(System.currentTimeMillis())) + ") " + pMessage + "\n", doc.getStyle("Info"));
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
scroll();
}
});
} catch (BadLocationException ignored) {
}
}
private void doTestSetTextWithGuardMarks() throws BadLocationException {
StyledDocument doc = editor.doc;
doc.insertString(0, "abcdef", null);
Position p = doc.createPosition(1);
assertTrue(!GuardUtils.isGuarded(doc, 1));
NbDocument.markGuarded(doc, 1, 3);
// As of #174294 the GuardedDocument.isPosGuarded returns false
// at the begining of an intra-line guarded section since an insert is allowed there.
assertFalse(GuardUtils.isGuarded(doc, 1));
assertTrue(GuardUtils.isGuarded(doc, 2));
doc.insertString(1, "x", null);
assertEquals(2, p.getOffset());
assertTrue(GuardUtils.isGuarded(doc, 3));
assertTrue(!GuardUtils.isGuarded(doc, 1));
doc.insertString(4, "x", null);
assertEquals(2, p.getOffset());
assertTrue(GuardUtils.isGuarded(doc, 4));
assertTrue(GuardUtils.isGuarded(doc, 3));
assertTrue(GuardUtils.isGuarded(doc, 5));
assertFalse(GuardUtils.isGuarded(doc, 2));
assertTrue(!GuardUtils.isGuarded(doc, 1));
GuardUtils.dumpGuardedAttr(doc);
doc.remove(1, 1);
assertEquals(1, p.getOffset());
}
private void addTileWarning(StyledDocument doc, Colony colony,
String messageId, Tile tile) {
if (messageId == null || !Messages.containsKey(messageId)) return;
StringTemplate t = StringTemplate.template(messageId)
.addStringTemplate("%location%",
tile.getColonyTileLocationLabel(colony));
try {
doc.insertString(doc.getLength(), "\n\n" + Messages.message(t),
doc.getStyle("regular"));
} catch (Exception e) {
logger.log(Level.WARNING, "Tile warning fail", e);
}
}
public void testOpenCSS() throws Exception {
StyledDocument doc = prepare("performance.css");
doc.insertString(0, "selector{color:green}", null);
waitTimeout();
doc.insertString(doc.getEndPosition().getOffset() - 1, "sx{c:red}", null);
waitTimeout();
for (LogRecord log : timerHandler.logs) {
verify(log, 200, 800);
}
}
@Override
public void insertString (StyledDocument sd, Style style) throws BadLocationException {
sd.insertString(sd.getLength(), toInsert, style);
}
private static void insertDefault(StyledDocument doc, String text)
throws BadLocationException {
doc.insertString(doc.getLength(), text, DEFAULT_STYLE);
}
private void addDiagnosticsText(String text, Style style) throws BadLocationException {
StyledDocument document = diagnosticsView.getStyledDocument();
document.insertString(document.getLength(), text, style);
diagnosticsScroll.updateUI();
}
@Override
public void defaultAction(JTextComponent jtc) {
logger.log(Level.FINER, "Accepted name completion: {0}", configurationMeta.getId());
try {
StyledDocument doc = (StyledDocument) jtc.getDocument();
// calculate the amount of chars to remove (by default from property start up to caret position)
int lenToRemove = caretOffset - propStartOffset;
int equalSignIndex = -1;
if (overwrite) {
// NOTE: the editor removes by itself the word at caret when ctrl + enter is pressed
// the document state here is different from when the completion was invoked thus we have to
// find again the offset of the equal sign in the line
Element lineElement = doc.getParagraphElement(caretOffset);
String line = doc.getText(lineElement.getStartOffset(), lineElement.getEndOffset() - lineElement.getStartOffset());
equalSignIndex = line.indexOf('=');
int colonIndex = line.indexOf(':');
if (equalSignIndex >= 0) {
// from property start to equal sign
lenToRemove = lineElement.getStartOffset() + equalSignIndex - propStartOffset;
} else if (colonIndex >= 0) {
// from property start to colon
lenToRemove = lineElement.getStartOffset() + colonIndex - propStartOffset;
} else {
// from property start to end of line (except line terminator)
lenToRemove = lineElement.getEndOffset() - 1 - propStartOffset;
}
}
// remove characters from the property name start offset
doc.remove(propStartOffset, lenToRemove);
// add some useful chars depending on data type and presence of successive equal signs
final String dataType = configurationMeta.getType();
final boolean isSequence = dataType.contains("List") || dataType.contains("Set") || dataType.contains("[]");
final boolean preferArray = NbPreferences.forModule(PrefConstants.class)
.getBoolean(PrefConstants.PREF_ARRAY_NOTATION, false);
final boolean needEqualSign = !(overwrite && equalSignIndex >= 0);
StringBuilder sb = new StringBuilder(getText());
boolean continueCompletion = false;
int goBack = 0;
if (dataType.contains("Map")) {
sb.append(".");
continueCompletion = canCompleteKey();
} else if (isSequence) {
if (preferArray) {
sb.append("[]");
goBack = 1;
if (needEqualSign) {
sb.append("=");
goBack++;
}
} else {
if (needEqualSign) {
sb.append("=");
continueCompletion = canCompleteValue();
}
}
} else if (needEqualSign) {
sb.append("=");
continueCompletion = canCompleteValue();
}
doc.insertString(propStartOffset, sb.toString(), null);
if (goBack != 0) {
jtc.setCaretPosition(jtc.getCaretPosition() - goBack);
}
// optinally close the code completion box
if (!continueCompletion) {
Completion.get().hideAll();
}
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
@RandomlyFails () // NB-Core-Build #9365: Unstable
public void testCloneModifyClose() throws Exception {
InstanceContent ic = new InstanceContent();
Lookup context = new AbstractLookup(ic);
final CES ces = createSupport(context, ic);
ic.add(ces);
ic.add(10);
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
ces.open();
}
});
final CloneableTopComponent tc = (CloneableTopComponent) ces.findPane();
assertNotNull("Component found", tc);
final CloneableTopComponent tc2 = tc.cloneTopComponent();
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
tc2.open();
tc2.requestActive();
}
});
ces.openDocument();
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
assertEquals("Two panes are open", 2, ces.getOpenedPanes().length);
}
});
StyledDocument doc = ces.getDocument();
assertNotNull("Document is opened", doc);
doc.insertString(0, "Ahoj", null);
assertTrue("Is modified", ces.isModified());
assertNotNull("Savable present", tc.getLookup().lookup(Savable.class));
assertNotNull("Savable present too", tc2.getLookup().lookup(Savable.class));
assertTrue("First component closes without questions", tc.close());
Savable save3 = tc2.getLookup().lookup(Savable.class);
assertNotNull("Savable still present", save3);
save3.save();
assertEquals("Saved", "Ahoj", Env.LAST_ONE.output);
assertTrue("Can be closed without problems", tc2.close());
}
private void showDescription() {
StyledDocument doc = descValue.getStyledDocument();
final Boolean matchCase = matchCaseValue.isSelected();
try {
doc.remove(0, doc.getLength());
ModuleDependency[] deps = getSelectedDependencies();
if (deps.length != 1) {
return;
}
String longDesc = deps[0].getModuleEntry().getLongDescription();
if (longDesc != null) {
doc.insertString(0, longDesc, null);
}
String filterText = filterValue.getText().trim();
if (filterText.length() != 0 && !FILTER_DESCRIPTION.equals(filterText)) {
doc.insertString(doc.getLength(), "\n\n", null); // NOI18N
Style bold = doc.addStyle(null, null);
bold.addAttribute(StyleConstants.Bold, Boolean.TRUE);
doc.insertString(doc.getLength(), getMessage("TEXT_matching_filter_contents"), bold);
doc.insertString(doc.getLength(), "\n", null); // NOI18N
if (filterText.length() > 0) {
String filterTextLC = matchCase?filterText:filterText.toLowerCase(Locale.US);
Style match = doc.addStyle(null, null);
match.addAttribute(StyleConstants.Background, UIManager.get("selection.highlight")!=null?
UIManager.get("selection.highlight"):new Color(246, 248, 139));
boolean isEven = false;
Style even = doc.addStyle(null, null);
even.addAttribute(StyleConstants.Background, UIManager.get("Panel.background"));
if (filterer == null) {
return; // #101776
}
for (String hit : filterer.getMatchesFor(filterText, deps[0])) {
int loc = doc.getLength();
doc.insertString(loc, hit, (isEven ? even : null));
int start = (matchCase?hit:hit.toLowerCase(Locale.US)).indexOf(filterTextLC);
while (start != -1) {
doc.setCharacterAttributes(loc + start, filterTextLC.length(), match, true);
start = hit.toLowerCase(Locale.US).indexOf(filterTextLC, start + 1);
}
doc.insertString(doc.getLength(), "\n", (isEven ? even : null)); // NOI18N
isEven ^= true;
}
} else {
Style italics = doc.addStyle(null, null);
italics.addAttribute(StyleConstants.Italic, Boolean.TRUE);
doc.insertString(doc.getLength(), getMessage("TEXT_no_filter_specified"), italics);
}
}
descValue.setCaretPosition(0);
} catch (BadLocationException e) {
Util.err.notify(ErrorManager.INFORMATIONAL, e);
}
}
private void updateFramesImpl(JEditorPane pane, boolean rawData) throws BadLocationException {
Style defaultStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
StyledDocument doc = (StyledDocument)pane.getDocument();
Style timingStyle = doc.addStyle("timing", defaultStyle);
StyleConstants.setForeground(timingStyle, Color.lightGray);
Style infoStyle = doc.addStyle("comment", defaultStyle);
StyleConstants.setForeground(infoStyle, Color.darkGray);
StyleConstants.setBold(infoStyle, true);
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
pane.setText("");
StringBuilder sb = new StringBuilder();
int lastFrameType = -1;
for (Network.WebSocketFrame f : wsRequest.getFrames()) {
int opcode = f.getOpcode();
if (opcode == 0) { // "continuation frame"
opcode = lastFrameType;
} else {
lastFrameType = opcode;
}
if (opcode == 1) { // "text frame"
if (!rawData) {
doc.insertString(doc.getLength(), formatter.format(f.getTimestamp()), timingStyle);
doc.insertString(doc.getLength(), f.getDirection() == Network.Direction.SEND ? " SENT " : " RECV ", timingStyle);
}
doc.insertString(doc.getLength(), f.getPayload()+"\n", defaultStyle);
} else if (opcode == 2) { // "binary frame"
if (!rawData) {
doc.insertString(doc.getLength(), formatter.format(f.getTimestamp()), timingStyle);
doc.insertString(doc.getLength(), f.getDirection() == Network.Direction.SEND ? " SENT " : " RECV ", timingStyle);
}
// XXX: binary data???
doc.insertString(doc.getLength(), f.getPayload()+"\n", defaultStyle);
} else if (opcode == 8) { // "close frame"
if (!rawData) {
doc.insertString(doc.getLength(), formatter.format(f.getTimestamp()), timingStyle);
doc.insertString(doc.getLength(), f.getDirection() == Network.Direction.SEND ? " SENT " : " RECV ", timingStyle);
}
doc.insertString(doc.getLength(), "Frame closed\n", infoStyle);
}
}
data = sb.toString();
pane.setCaretPosition(0);
}