下面列出了怎么用javax.swing.text.EditorKit的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Get searchable editor kit for the given kit.
* @param kit non-null kit.
* @return non-null searchable kit.
*/
public static SearchableEditorKit getSearchableKit(EditorKit kit) {
SearchableEditorKit searchableKit;
if (kit instanceof SearchableEditorKit) {
searchableKit = ((SearchableEditorKit)kit);
} else {
synchronized (kit2searchable) {
searchableKit = kit2searchable.get(kit);
if (searchableKit == null) {
searchableKit = new DefaultSearchableKit(kit);
registerSearchableKit(kit, searchableKit);
}
}
}
return searchableKit;
}
void read(InputStream in, Document doc) throws IOException
{
EditorKit kit = getEditorKit();
try
{
kit.read(in, doc, 0);
} catch (ChangedCharSetException ccse)
{
// ignored, may be in the future will be processed
throw ccse;
} catch (BadLocationException ble)
{
throw new IOException(ble);
}
}
/**
* Initialize method.
*/
private void initialize() {
EditorKit editorKit = new SQLEditorKit();
sqlText.setEditorKitForContentType("text/sql", editorKit);
sqlText.setContentType("text/sql");
String rowDef = "2dlu,p,2dlu,p,fill:220dlu,10dlu,p,2dlu";
String colDef = "2dlu,left:45dlu,2dlu,fill:140dlu:grow,fill:60dlu,2dlu,fill:60dlu,2dlu";
FormLayout layout = new FormLayout(colDef, rowDef);
setLayout(layout);
CellConstraints cons = new CellConstraints();
add(getComponent1(), cons.xywh(2, 2, 1, 1));
add(getEntityName(), cons.xywh(4, 2, 4, 1));
add(getMainTabbedPane(), cons.xywh(2, 4, 6, 2));
add(getOkButton(), cons.xywh(5, 7, 1, 1));
add(getCancelButton(), cons.xywh(7, 7, 1, 1));
}
private Document createDocument(EditorKit kit, URL page)
{
// we have pageProperties, because we can be in situation that
// old page is being removed & new page is not yet created...
// we need somewhere store important data.
Document doc = kit.createDefaultDocument();
if (pageProperties != null)
{
// transfer properties discovered in stream to the
// document property collection.
for (Enumeration<String> e = pageProperties.keys(); e
.hasMoreElements();)
{
Object key = e.nextElement();
doc.putProperty(key, pageProperties.get(key));
}
}
if (doc.getProperty(Document.StreamDescriptionProperty) == null)
{
doc.putProperty(Document.StreamDescriptionProperty, page);
}
return doc;
}
public static RandomTestContainer createContainer(EditorKit kit) throws Exception {
// Ensure the new view hierarchy is turned on
System.setProperty("org.netbeans.editor.linewrap", "true");
// Set the property for synchronous highlights firing since otherwise
// the repeatability of problems with view hierarchy is none or limited.
System.setProperty("org.netbeans.editor.sync.highlights", "true");
System.setProperty("org.netbeans.editor.linewrap.edt", "true");
RandomTestContainer container = new RandomTestContainer();
EditorPaneTesting.initContainer(container, kit);
DocumentTesting.initContainer(container);
DocumentTesting.initUndoManager(container);
container.addCheck(new ViewHierarchyCheck());
JEditorPane pane = EditorPaneTesting.getEditorPane(container);
pane.putClientProperty("text-line-wrap", "words"); // SimpleValueNames.TEXT_LINE_WRAP
return container;
}
/** Attempt to find the editor keystroke for the given editor action. */
private KeyStroke[] findEditorKeys(String editorActionName, KeyStroke defaultKey, JTextComponent component) {
// This method is implemented due to the issue
// #25715 - Attempt to search keymap for the keybinding that logically corresponds to the action
KeyStroke[] ret = new KeyStroke[] { defaultKey };
if (component != null) {
TextUI componentUI = component.getUI();
Keymap km = component.getKeymap();
if (componentUI != null && km != null) {
EditorKit kit = componentUI.getEditorKit(component);
if (kit instanceof BaseKit) {
Action a = ((BaseKit)kit).getActionByName(editorActionName);
if (a != null) {
KeyStroke[] keys = km.getKeyStrokesForAction(a);
if (keys != null && keys.length > 0) {
ret = keys;
}
}
}
}
}
return ret;
}
/** Attempt to find the editor keystroke for the given editor action. */
private KeyStroke[] findEditorKeys(String editorActionName, KeyStroke defaultKey, JTextComponent component) {
// This method is implemented due to the issue
// #25715 - Attempt to search keymap for the keybinding that logically corresponds to the action
KeyStroke[] ret = new KeyStroke[] { defaultKey };
if (component != null) {
TextUI componentUI = component.getUI();
Keymap km = component.getKeymap();
if (componentUI != null && km != null) {
EditorKit kit = componentUI.getEditorKit(component);
if (kit instanceof BaseKit) {
Action a = ((BaseKit)kit).getActionByName(editorActionName);
if (a != null) {
KeyStroke[] keys = km.getKeyStrokesForAction(a);
if (keys != null && keys.length > 0) {
ret = keys;
}
}
}
}
}
return ret;
}
@Override
protected void saveFromKitToStream(StyledDocument doc, EditorKit kit, OutputStream stream)
throws IOException, BadLocationException {
if (guardedProvider != null) {
Charset c = FileEncodingQuery.getEncoding(this.getDataObject().getPrimaryFile());
Writer writer = guardedProvider.createGuardedWriter(stream, c);
try {
kit.write(writer, doc, 0, doc.getLength());
} finally {
writer.close();
}
} else {
super.saveFromKitToStream(doc, kit, stream);
}
}
public AdvancedActionPanel(AntProjectCookie project, Set/*<TargetLister.Target>*/ allTargets) {
this.project = project;
this.allTargets = allTargets;
initComponents();
Mnemonics.setLocalizedText(targetLabel, NbBundle.getMessage(AdvancedActionPanel.class, "AdvancedActionsPanel.targetLabel.text"));
Mnemonics.setLocalizedText(targetDescriptionLabel, NbBundle.getMessage(AdvancedActionPanel.class, "AdvancedActionsPanel.targetDescriptionLabel.text"));
Mnemonics.setLocalizedText(propertiesLabel, NbBundle.getMessage(AdvancedActionPanel.class, "AdvancedActionsPanel.propertiesLabel.text"));
Mnemonics.setLocalizedText(verbosityLabel, NbBundle.getMessage(AdvancedActionPanel.class, "AdvancedActionsPanel.verbosityLabel.text"));
// Hack; EditorKit does not permit "fallback" kits, so we have to
// mimic what the IDE itself does:
EditorKit kit = propertiesPane.getEditorKit();
String clazz = kit.getClass().getName();
if (clazz.equals("javax.swing.text.DefaultEditorKit") || // NOI18N
clazz.equals("javax.swing.JEditorPane$PlainEditorKit")) { // NOI18N
propertiesPane.setEditorKit(JEditorPane.createEditorKitForContentType("text/plain")); // NOI18N
}
// Make ENTER run OK, not change the combo box.
targetComboBox.getInputMap().remove(KeyStroke.getKeyStroke("ENTER")); // NOI18N
initializeFields();
}
public Context(final EditorKit kit, final String textWithPipe) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
pane = new JEditorPane();
pane.setEditorKit(kit);
Document doc = pane.getDocument();
// Required by Java's default key typed
doc.putProperty(Language.class, JavaTokenId.language());
doc.putProperty("mimeType", "text/x-java");
int caretOffset = textWithPipe.indexOf('|');
String text;
if (caretOffset != -1) {
text = textWithPipe.substring(0, caretOffset) + textWithPipe.substring(caretOffset + 1);
} else {
text = textWithPipe;
}
pane.setText(text);
pane.setCaretPosition((caretOffset != -1) ? caretOffset : doc.getLength());
}
});
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public void actionPerformed(ActionEvent evt) {
// Find the right action for the corresponding editor kit
JTextComponent component = getTextComponent(evt);
if (component != null) {
TextUI ui = component.getUI();
if (ui != null) {
EditorKit kit = ui.getEditorKit(component);
if (kit != null) {
Action action = EditorUtilities.getAction(kit, actionName);
if (action != null) {
action.actionPerformed(evt);
} else {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Action '" + actionName + "' not found in editor kit " + kit + '\n'); // NOI18N
}
}
}
}
}
}
public Typing(final EditorKit kit, final String textWithPipe) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
pane = new JEditorPane();
pane.setEditorKit(kit);
Document doc = pane.getDocument();
// Required by Java's default key typed
doc.putProperty(Language.class, HTMLTokenId.language());
doc.putProperty("mimeType", "text/html");
int caretOffset = textWithPipe.indexOf('|');
String text;
if (caretOffset != -1) {
text = textWithPipe.substring(0, caretOffset) + textWithPipe.substring(caretOffset + 1);
} else {
text = textWithPipe;
}
pane.setText(text);
pane.setCaretPosition((caretOffset != -1) ? caretOffset : doc.getLength());
}
});
} catch (InterruptedException | InvocationTargetException e) {
throw new RuntimeException(e.getCause());
}
}
@Override
protected void loadFromStreamToKit(StyledDocument doc, InputStream stream, EditorKit kit)
throws IOException, BadLocationException {
Exception e = new Exception();
StringWriter sw = new StringWriter(500);
PrintWriter pw = new PrintWriter(sw);
pw.println("loadFromStreamToKit"
+ " this:[" + Integer.toHexString(System.identityHashCode(doc)) + "]"
+ " thread:" + Thread.currentThread().getName());
e.printStackTrace(pw);
pw.flush();
inits.add(new Exception(sw.toString()));
super.loadFromStreamToKit(doc, stream, kit);
}
@Override
protected StyledDocument createStyledDocument(EditorKit kit) {
StyledDocument doc = super.createStyledDocument(kit);
//#174763 workaround - there isn't any elegant place where to place
//a code which needs to be run after document's COMPLETE initialization.
//DataEditorSupport.createStyledDocument() creates the document via the
//EditorKit.createDefaultDocument(), but some of the important properties
//like Document.StreamDescriptionProperty or mimetype are set as the
//document properties later.
//A hacky solution is that a Runnable can be set to the postInitRunnable property
//in the EditorKit.createDefaultDocument() and the runnable is run
//once the document is completely initialized.
Runnable postInitRunnable = (Runnable)doc.getProperty("postInitRunnable"); //NOI18N
if(postInitRunnable != null) {
postInitRunnable.run();
}
return doc;
}
@Override
protected void saveFromKitToStream(StyledDocument doc, EditorKit kit, OutputStream stream) throws IOException, BadLocationException {
Parameters.notNull("doc", doc);
Parameters.notNull("kit", kit);
String foundEncoding = (String) doc.getProperty(DOCUMENT_SAVE_ENCODING);
String encoding = foundEncoding != null ? foundEncoding : defaulEncoding;
Charset charset = Charset.forName("UTF-8"); //NOI18N
try {
charset = Charset.forName(encoding);
} catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
LOGGER.log(Level.INFO, "Illegal charset found: {0}, defaulted to UTF-8 as warned by dialog", encoding);
}
writeByteOrderMark(charset, stream);
super.saveFromKitToStream(doc, kit, stream);
}
private FacesConfig initFacesConfig() throws IOException, InterruptedException {
assertNotNull(getJsfDO());
editorSupport = (JSFConfigEditorSupport) getJsfDO().createCookie(JSFConfigEditorSupport.class);
assertNotNull(editorSupport);
Lookup lookup = getJsfDO().getLookup();
assertNotNull(lookup);
Util.registerXMLKit();
EditorKit kit = JSFConfigEditorSupport.getEditorKit("text/x-jsf+xml");
assert (kit instanceof XMLKit);
editorSupport.edit();
// MultiViewHandler h = MultiViews.findMultiViewHandler(TopComponent.getRegistry().getActivated());
// h.requestVisible(h.getPerspectives()[2]);
((MultiViewCloneableTopComponent) TopComponent.getRegistry().getActivated()).getSubComponents()[1].activate();
((PageFlowView) TopComponent.getRegistry().getActivated()).getMultiview().getEditorPane();
JSFConfigModel model = ConfigurationUtils.getConfigModel(getJsfDO().getPrimaryFile(), true);
assertNotNull(model);
FacesConfig myFacesConfig = model.getRootComponent();
assertNotNull(myFacesConfig);
return myFacesConfig;
}
/** Attempt to find the editor keystroke for the given editor action. */
private KeyStroke[] findEditorKeys(String editorActionName, KeyStroke defaultKey, JTextComponent component) {
// This method is implemented due to the issue
// #25715 - Attempt to search keymap for the keybinding that logically corresponds to the action
KeyStroke[] ret = new KeyStroke[] { defaultKey };
if (component != null) {
TextUI componentUI = component.getUI();
Keymap km = component.getKeymap();
if (componentUI != null && km != null) {
EditorKit kit = componentUI.getEditorKit(component);
if (kit instanceof BaseKit) {
Action a = ((BaseKit)kit).getActionByName(editorActionName);
if (a != null) {
KeyStroke[] keys = km.getKeyStrokesForAction(a);
if (keys != null && keys.length > 0) {
ret = keys;
}
}
}
}
}
return ret;
}
private Formatter getFormatter() {
if (legacyFormatter == null) {
EditorKit kit = MimeLookup.getLookup(mimePath).lookup(EditorKit.class);
if (kit != null) {
try {
Method createFormatterMethod = kit.getClass().getDeclaredMethod("createFormatter"); //NOI18N
legacyFormatter = createFormatterMethod.invoke(kit);
} catch (Exception e) {
legacyFormatter = e;
}
} else {
legacyFormatter = NO_FORMATTER;
}
}
return legacyFormatter instanceof Formatter ? (Formatter) legacyFormatter : null;
}
/**
* Print into given container.
*
* @param container printing container into which the printing will be done.
* @param usePrintColoringMap use printing coloring settings instead
* of the regular ones.
* @param lineNumberEnabled if set to false the line numbers will not be printed.
* If set to true the visibility of line numbers depends on the settings
* for the line number visibility.
* @param startOffset start offset of text to print
* @param endOffset end offset of text to print
*/
public void print(PrintContainer container, boolean usePrintColoringMap, boolean lineNumberEnabled, int startOffset,
int endOffset) {
readLock();
try {
EditorUI editorUI;
EditorKit kit = getEditorKit();
if (kit instanceof BaseKit) {
editorUI = ((BaseKit) kit).createPrintEditorUI(this, usePrintColoringMap, lineNumberEnabled);
} else {
editorUI = new EditorUI(this, usePrintColoringMap, lineNumberEnabled);
}
DrawGraphics.PrintDG printDG = new DrawGraphics.PrintDG(container);
DrawEngine.getDrawEngine().draw(printDG, editorUI, startOffset, endOffset, 0, 0, Integer.MAX_VALUE);
} catch (BadLocationException e) {
LOG.log(Level.WARNING, null, e);
} finally {
readUnlock();
}
}
public static EditorKit getEditorKit(DataObject dataObject) {
FileObject fileObject = dataObject.getPrimaryFile();
String mimePath = fileObject.getMIMEType();
Lookup lookup = MimeLookup.getLookup(MimePath.parse(mimePath));
EditorKit kit = lookup.lookup(EditorKit.class);
return kit;
}
private String getMimeType() {
EditorKit ek = component.getUI().getEditorKit(component);
String mimeType;
if (ek != null) {
mimeType = ek.getContentType();
} else if (component.getDocument() != null) {
mimeType = DocumentUtilities.getMimeType(component.getDocument());
} else {
mimeType = "";
}
return mimeType;
}
/**
* Invokes the <code>getEditorKit</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public EditorKit getEditorKit(JTextComponent a) {
EditorKit returnValue =
((TextUI) (uis.elementAt(0))).getEditorKit(a);
for (int i = 1; i < uis.size(); i++) {
((TextUI) (uis.elementAt(i))).getEditorKit(a);
}
return returnValue;
}
/**
* Invokes the <code>getEditorKit</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public EditorKit getEditorKit(JTextComponent a) {
EditorKit returnValue =
((TextUI) (uis.elementAt(0))).getEditorKit(a);
for (int i = 1; i < uis.size(); i++) {
((TextUI) (uis.elementAt(i))).getEditorKit(a);
}
return returnValue;
}
/**
* Invokes the <code>getEditorKit</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public EditorKit getEditorKit(JTextComponent a) {
EditorKit returnValue =
((TextUI) (uis.elementAt(0))).getEditorKit(a);
for (int i = 1; i < uis.size(); i++) {
((TextUI) (uis.elementAt(i))).getEditorKit(a);
}
return returnValue;
}
private JPanel createPanel(String text)
{
JPanel panel = new JPanel(new GridLayout(1, 1));
JEditorPane editorPane = new JEditorPane();
editorPane.setBorder(GuiUtil.createEmptyBorder());
editorPane.setEditable(false);
if (Platform.isMac())
{
editorPane.setForeground(UIManager.getColor("Label.foreground"));
editorPane.setBackground(UIManager.getColor("Label.background"));
}
else
{
editorPane.setForeground(Color.black);
editorPane.setBackground(Color.white);
}
panel.add(editorPane);
EditorKit editorKit =
JEditorPane.createEditorKitForContentType("text/html");
editorPane.setEditorKit(editorKit);
editorPane.setText(text);
editorPane.addHyperlinkListener(new HyperlinkListener()
{
public void hyperlinkUpdate(HyperlinkEvent event)
{
HyperlinkEvent.EventType type = event.getEventType();
if (type == HyperlinkEvent.EventType.ACTIVATED)
{
URL url = event.getURL();
if (! Platform.openInExternalBrowser(url))
m_messageDialogs.showError(null,
i18n("MSG_ABOUT_OPEN_URL_FAIL"),
"", false);
}
}
});
return panel;
}
/**
* Invokes the <code>getEditorKit</code> method on each UI handled by this object.
*
* @return the value obtained from the first UI, which is
* the UI obtained from the default <code>LookAndFeel</code>
*/
public EditorKit getEditorKit(JTextComponent a) {
EditorKit returnValue =
((TextUI) (uis.elementAt(0))).getEditorKit(a);
for (int i = 1; i < uis.size(); i++) {
((TextUI) (uis.elementAt(i))).getEditorKit(a);
}
return returnValue;
}
@Test
public void testGetAction() throws Exception {
EditorKit editorKit = new DefaultEditorKit();
String actionName = DefaultEditorKit.backwardAction;
Action result = EditorUtilities.getAction(editorKit, actionName);
for (Action expected : editorKit.getActions()) {
if (actionName.equals(expected.getValue(Action.NAME))) {
assertEquals(expected, result);
return;
}
}
fail("Action " + actionName + " not found.");
}
@Override
protected StyledDocument createStyledDocument (EditorKit kit) {
StyledDocument doc = super.createStyledDocument(kit);
// Enter the file object in to InputAtrributes. It can be used by lexer.
InputAttributes attributes = new InputAttributes();
FileObject fileObject = NbEditorUtilities.getFileObject(doc);
final GsfLanguage lng = language.getGsfLanguage();
if (lng != null) {
attributes.setValue(lng.getLexerLanguage(), FileObject.class, fileObject, false);
}
doc.putProperty(InputAttributes.class, attributes);
return doc;
}
private static EditorKit getBaseEditorKit() {
Reference<EditorKit> r = plainKitRef;
EditorKit ek = r.get();
if (ek != null) {
return ek;
}
ek = MimeLookup.getLookup(MimePath.parse("text/plain")).lookup(EditorKit.class);
synchronized (OverrideEditorActions.class) {
if (r == plainKitRef) {
plainKitRef = new WeakReference<>(ek);
}
}
return ek;
}
private static Action findDelegate(String id) {
EditorKit ek = getBaseEditorKit();
if (ek == null) {
return null;
}
if (ek instanceof BaseKit) {
BaseKit bk = (BaseKit)ek;
return bk.getActionByName(id);
} else {
// PENDING: find the action by ID from the Action[] map-array.
return null;
}
}