下面列出了怎么用javax.swing.JEditorPane的API类实例代码及写法,或者点击链接到github查看源代码。
/**Currently, this method is supposed to be runned inside the AWT thread.
* If this condition is not fullfilled, an IllegalStateException is
* thrown. Do NOT modify this behaviour, or deadlock (or even Swing
* or NetBeans winsys data corruption) may occur.
*
* Currently threading model of this method is compatible with
* editor code completion threading model. Revise if this changes
* in future.
*/
private void testPerform(PrintWriter out, PrintWriter log,
JEditorPane editor,
boolean unsorted,
String assign,
int lineIndex,
int queryType) throws BadLocationException, IOException {
if (!SwingUtilities.isEventDispatchThread())
throw new IllegalStateException("The testPerform method may be called only inside AWT event dispatch thread.");
BaseDocument doc = Utilities.getDocument(editor);
int lineOffset = Utilities.getRowStartFromLineOffset(doc, lineIndex -1);
editor.grabFocus();
editor.getCaret().setDot(lineOffset);
doc.insertString(lineOffset, assign, null);
reparseDocument((DataObject) doc.getProperty(doc.StreamDescriptionProperty));
completionQuery(out, log, editor, unsorted, queryType);
}
/**
* Sets the font size.
*
* @param e the action event
*/
public void actionPerformed(ActionEvent e) {
JEditorPane editor = getEditor(e);
if (editor != null) {
int size = this.size;
if ((e != null) && (e.getSource() == editor)) {
String s = e.getActionCommand();
try {
size = Integer.parseInt(s, 10);
} catch (NumberFormatException nfe) {
}
}
if (size != 0) {
MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setFontSize(attr, size);
setCharacterAttributes(editor, attr, false);
} else {
UIManager.getLookAndFeel().provideErrorFeedback(editor);
}
}
}
public void hyperlinkUpdate(HyperlinkEvent event) {
JEditorPane descriptionPane = (JEditorPane) event.getSource();
HyperlinkEvent.EventType type = event.getEventType();
if (type == HyperlinkEvent.EventType.ACTIVATED) {
try {
DemoUtilities.browse(event.getURL().toURI());
} catch (Exception e) {
e.printStackTrace();
System.err.println(e);
}
} else if (type == HyperlinkEvent.EventType.ENTERED) {
defaultCursor = descriptionPane.getCursor();
descriptionPane.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
} else if (type == HyperlinkEvent.EventType.EXITED) {
descriptionPane.setCursor(defaultCursor);
}
}
@RandomlyFails
public void testModelToViewCorrectness() throws Throwable {
for(String text : TEXTS) {
JEditorPane jep = createJep(text);
try {
checkModelToViewCorrectness(jep);
} catch (Throwable e) {
System.err.println("testModelToViewCorrectness processing {");
System.err.println(text);
System.err.println("} failed with:");
e.printStackTrace();
throw e;
} finally {
JFrame frame = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, jep);
if (frame != null) {
frame.dispose();
}
}
}
}
@Override
public JComponent createComponent() {
JScrollPane pane = new JScrollPane();
editorPane = new JEditorPane();
pane.setViewportView(editorPane);
if (scriptPath.endsWith(".js"))
editorPane.setContentType("text/javascript");
byte[] bs = framework.getEngine().getStream(scriptPath);
if (bs == null)
bs = new byte[]{};
try {
editorPane.setText(new String(bs, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (!saveScriptAction.isEnabled())
editorPane.setEditable(false);
return pane;
}
private boolean isExcludedProperty1(FormProperty prop) {
if (!Boolean.TRUE.equals(prop.getValue(EXCLUSION_DETERMINED))) {
prop.setValue(EXCLUSION_DETERMINED, true);
Object propOwner = prop.getPropertyContext().getOwner();
Class type = null;
if (propOwner instanceof RADComponent) {
type = ((RADComponent)propOwner).getBeanClass();
} else if (propOwner instanceof FormProperty) {
type = ((FormProperty)propOwner).getValueType();
}
String propName = prop.getName();
boolean excl = (Component.class.isAssignableFrom(type) && "name".equals(propName)) // NOI18N
|| (JEditorPane.class.isAssignableFrom(type) && "contentType".equals(propName)); // NOI18N
prop.setValue(EXCLUDE_FROM_RESOURCING, excl);
return excl;
}
return false;
}
/**
* Sets the font family.
*
* @param e the event
*/
public void actionPerformed(ActionEvent e) {
JEditorPane editor = getEditor(e);
if (editor != null) {
String family = this.family;
if ((e != null) && (e.getSource() == editor)) {
String s = e.getActionCommand();
if (s != null) {
family = s;
}
}
if (family != null) {
MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setFontFamily(attr, family);
setCharacterAttributes(editor, attr, false);
} else {
UIManager.getLookAndFeel().provideErrorFeedback(editor);
}
}
}
/**
* Returns identifier currently selected in editor or <code>null</code>.
*
* @return identifier currently selected in editor or <code>null</code>
*/
@Override
public String getSelectedIdentifier () {
JEditorPane ep = contextDispatcher.getCurrentEditor ();
if (ep == null) {
return null;
}
Caret caret = ep.getCaret();
if (caret == null) {
// No caret => no selected text
return null;
}
String s = ep.getSelectedText ();
if (s == null) {
return null;
}
if (Utilities.isJavaIdentifier (s)) {
return s;
}
return null;
}
void connect( JTree errorTree, JComboBox severityComboBox,
JCheckBox tasklistCheckBox, JPanel customizerPanel,
JEditorPane descriptionTextArea) {
this.errorTree = errorTree;
this.severityComboBox = severityComboBox;
this.tasklistCheckBox = tasklistCheckBox;
this.customizerPanel = customizerPanel;
this.descriptionTextArea = descriptionTextArea;
valueChanged( null );
errorTree.addKeyListener(this);
errorTree.addMouseListener(this);
errorTree.getSelectionModel().addTreeSelectionListener(this);
severityComboBox.addActionListener(this);
tasklistCheckBox.addChangeListener(this);
}
private static void setup() {
/**
* Note the input type is not restricted to "submit". Types "image",
* "checkbox", "radio" have the same problem.
*/
html = new JEditorPane("text/html",
"<html><body><form action=\"http://localhost.cgi\">"
+ "<input type=submit name=submit value=\"submit\"/>"
+ "</form></body></html>");
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(html, BorderLayout.CENTER);
frame.setSize(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void testRenameTheDocumentWhilechangingTheTimestamp() throws Exception {
Document doc = edit.openDocument();
assertFalse("Not Modified", edit.isModified());
doc.insertString(0, "Base change\n", null);
assertTrue("Is Modified", edit.isModified());
edit.open();
waitEQ();
JEditorPane[] arr = getPanes();
assertNotNull("There is one opened pane", arr);
obj.getFolder().rename("newName");
assertEquals("Last modified incremented by 10000", lastM + 10000, obj.getPrimaryFile().lastModified().getTime());
assertTrue("Name contains newName: " + obj.getPrimaryFile(), obj.getPrimaryFile().getPath().contains("newName/"));
waitEQ();
edit.saveDocument();
if (DD.error != null) {
fail("Error in dialog:\n" + DD.error);
}
}
protected final void jsonMinify(final Node[] activatedNodes) {
final EditorCookie editorCookie
= Utilities.actionsGlobalContext().lookup(EditorCookie.class);
for (final JEditorPane pane : editorCookie.getOpenedPanes()) {
if (pane.isShowing()
&& pane.getSelectionEnd() > pane.getSelectionStart()) {
try {
StringSelection content = new StringSelection(selectedSourceAsMinify(pane));
Toolkit.getDefaultToolkit().getSystemClipboard().
setContents(content, content);
return;
} catch (final HeadlessException e) {
org.openide.ErrorManager.getDefault().notify(e);
}
}
}
}
/**
* Sets the foreground color.
*
* @param e the action event
*/
public void actionPerformed(ActionEvent e) {
JEditorPane editor = getEditor(e);
if (editor != null) {
Color fg = this.fg;
if ((e != null) && (e.getSource() == editor)) {
String s = e.getActionCommand();
try {
fg = Color.decode(s);
} catch (NumberFormatException nfe) {
}
}
if (fg != null) {
MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setForeground(attr, fg);
setCharacterAttributes(editor, attr, false);
} else {
UIManager.getLookAndFeel().provideErrorFeedback(editor);
}
}
}
public void testSelectionAndInsertTab() throws Exception {
loggingOn();
RandomTestContainer container = createContainer();
JEditorPane pane = container.getInstance(JEditorPane.class);
Document doc = pane.getDocument();
doc.putProperty("mimeType", "text/plain");
ViewHierarchyRandomTesting.initRandomText(container);
RandomTestContainer.Context context = container.context();
DocumentTesting.insert(context, 0,
" osen \n\n\n esl\t\ta \t\t \n\n\nabcd\td m\t\tabcdef\te\t\tab\tcdef\tef\tkojd p\t\t \n\n\n t\t vpjm\ta\ngooywzmj q\tugos\tdefy\t i xs us tg z"
);
EditorPaneTesting.setCaretOffset(context, 64);
EditorPaneTesting.moveOrSelect(context, SwingConstants.NORTH, false);
EditorPaneTesting.moveOrSelect(context, SwingConstants.SOUTH, true);
DocumentTesting.insert(context, 19, "g");
EditorPaneTesting.moveOrSelect(context, SwingConstants.EAST, true);
EditorPaneTesting.moveOrSelect(context, SwingConstants.NORTH, true);
EditorPaneTesting.moveOrSelect(context, SwingConstants.WEST, true);
EditorPaneTesting.performAction(context, pane, DefaultEditorKit.deletePrevCharAction);
EditorPaneTesting.performAction(context, pane, DefaultEditorKit.insertTabAction);
EditorPaneTesting.moveOrSelect(context, SwingConstants.EAST, false);
EditorPaneTesting.typeChar(context, 'f');
}
public static boolean canHandle(Node activatedNode) {
FileObject fileObject = CommandUtils.getFileObject(activatedNode);
if (fileObject == null) {
return false;
}
PhpProject project = PhpProjectUtils.getPhpProject(fileObject);
if (project == null) {
return false;
}
final EditorCookie editorCookie = activatedNode.getLookup().lookup(EditorCookie.class);
if (editorCookie == null) {
return false;
}
JEditorPane pane = Mutex.EVENT.readAccess(new Mutex.Action<JEditorPane>() {
@Override
public JEditorPane run() {
return NbDocument.findRecentEditorPane(editorCookie);
}
});
if (pane == null) {
return false;
}
return getTestMethod(pane.getDocument(), pane.getCaret().getDot()) != null;
}
public void loadPage(String url, final ActionListener listener)
throws IOException {
this.url = url;
pane = new JEditorPane();
pane.setContentType("text/html");
pane.addPropertyChangeListener("page", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
generate(0);
if (listener != null)
listener.actionPerformed(new ActionEvent(
HTMLPrintable.this, 0, "PageLoaded"));
}
});
pane.setPage(url);
}
@RandomlyFails // NB-Core-Build #1981, #1984
public void testInitializeOnBackground() throws Exception {
support.open();
class R implements Runnable {
JEditorPane p;
public void run() {
p = support.getOpenedPanes()[0];
}
}
R r = new R();
SwingUtilities.invokeAndWait(r);
assertNotNull(r.p);
if (r.p.getEditorKit() instanceof NbLikeEditorKit) {
NbLikeEditorKit nb = (NbLikeEditorKit)r.p.getEditorKit();
assertNotNull("call method called", nb.callThread);
if (nb.callThread.getName().contains("AWT")) {
fail("wrong thread: " + nb.callThread);
}
} else {
fail("Should use NbLikeEditorKit: " + r.p.getEditorKit());
}
}
JEditorPane getEditorPane() {
if (model != null) {
MultiViewElement el = model.getActiveElement();
if (el != null && el.getVisualRepresentation() instanceof Pane) {
Pane pane = (Pane)el.getVisualRepresentation();
return pane.getEditorPane();
}
}
return null;
}
/**
* Creates the new Panel and parses the supplied HTML. <br>
* <b> Supported Github Markdown: </b><i> Lists (unordered), Links, Images, Bold ('**' and '__'), Strikethrough, & Italics. </i>
*
* @param currentVersion The version of the Jar currently running.
*/
public GithubPanel(double currentVersion) {
this.version = currentVersion;
setTitle("MLGA Update");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
parseReleases();
} catch (Exception e1) {
e1.printStackTrace();
}
if (updates <= 0) {
return;
}
ed = new JEditorPane("text/html", html);
ed.setEditable(false);
ed.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
ed.setFont(new Font("Helvetica", 0, 12));
ed.addHyperlinkListener(he -> {
// Listen to link clicks and open them in the browser.
if (he.getEventType() == EventType.ACTIVATED && Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(he.getURL().toURI());
System.exit(0);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
});
final JScrollPane scrollPane = new JScrollPane(ed);
scrollPane.setPreferredSize(new Dimension(1100, 300));
add(scrollPane);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
/**
* Toggles the Underline attribute.
*
* @param e the action event
*/
public void actionPerformed(ActionEvent e) {
JEditorPane editor = getEditor(e);
if (editor != null) {
StyledEditorKit kit = getStyledEditorKit(editor);
MutableAttributeSet attr = kit.getInputAttributes();
boolean underline = (StyleConstants.isUnderline(attr)) ? false : true;
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setUnderline(sas, underline);
setCharacterAttributes(editor, sas, false);
}
}
@Override
protected void setUp() throws Exception {
super.setUp();
pane = new JEditorPane();
doc = pane.getDocument();
wh = new WhitespaceHighlighting(pane);
wh.testInitEnv(INDENT_ATTRS, TRAILING_ATTRS);
}
private JEditorPane findPane(Component component) {
while (component != null) {
if (component instanceof JEditorPane) {
return (JEditorPane) component;
}
component = component.getParent();
}
return null;
}
/**
*
* @param description
* the textfield that holds the forms description
* @param formContainer
* the container in which the editor form is sitting
* @param type
* BACK or FORWARD.
*/
public NavigateAction(JEditorPane description, JPanel formContainer, int type, FormData formData) {
this.formContainer = formContainer;
this.type = type;
this.formData = formData;
if (type == BACK) {
putValue(NAME, "back");
}
if (type == FORWARD) {
putValue(NAME, "next");
}
this.description = description;
}
protected void clickForTextPopup(EditorOperator eo, String menu) {
JEditorPaneOperator txt = eo.txtEditorPane();
JEditorPane epane = (JEditorPane) txt.getSource();
try {
Rectangle rct = epane.modelToView(epane.getCaretPosition());
txt.clickForPopup(rct.x, rct.y);
JPopupMenuOperator popup = new JPopupMenuOperator();
popup.pushMenu(menu);
} catch (BadLocationException ex) {
System.out.println("=== Bad location");
}
}
/**
* Toggles the Underline attribute.
*
* @param e the action event
*/
public void actionPerformed(ActionEvent e) {
JEditorPane editor = getEditor(e);
if (editor != null) {
StyledEditorKit kit = getStyledEditorKit(editor);
MutableAttributeSet attr = kit.getInputAttributes();
boolean underline = (StyleConstants.isUnderline(attr)) ? false : true;
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setUnderline(sas, underline);
setCharacterAttributes(editor, sas, false);
}
}
public static void reset() {
add(Component.class, JavaElement.class);
add(JList.class, JListJavaElement.class);
add(JTabbedPane.class, JTabbedPaneJavaElement.class);
add(JComboBox.class, JComboBoxJavaElement.class);
add(JTable.class, JTableJavaElement.class);
add(JTableHeader.class, JTableHeaderJavaElement.class);
add(JTree.class, JTreeJavaElement.class);
add(JToggleButton.class, JToggleButtonJavaElement.class);
add(JSpinner.class, JSpinnerJavaElement.class);
add(JProgressBar.class, JProgressBarJavaElement.class);
add(JSplitPane.class, JSplitPaneJavaElement.class);
add(JTextComponent.class, JTextComponentJavaElement.class);
add(EditorContainer.class, JTreeEditingContainerJavaElement.class);
add(JEditorPane.class, JEditorPaneJavaElement.class);
add(JMenuItem.class, JMenuItemJavaElement.class);
add(JSlider.class, JSliderJavaElement.class);
add(JSpinner.class, JSpinnerJavaElement.class);
add(DefaultEditor.class, DefaultEditorJavaElement.class);
add(JColorChooser.class, JColorChooserJavaElement.class);
add(JFileChooser.class, JFileChooserJavaElement.class);
add("com.jidesoft.swing.TristateCheckBox", JideTristateCheckBoxElement.class);
add("com.jidesoft.swing.CheckBoxListCellRenderer", JideCheckBoxListItemElement.class);
add("com.jidesoft.swing.CheckBoxTreeCellRenderer", JideCheckBoxTreeNodeElement.class);
add("com.jidesoft.spinner.DateSpinner", JideDateSpinnerElement.class);
add("com.jidesoft.swing.JideSplitPane", JideSplitPaneElement.class);
}
private int getOpenedCount(final CES ces) {
return Mutex.EVENT.readAccess(new Mutex.Action<Integer>() {
public Integer run() {
JEditorPane[] panes = ces.getOpenedPanes();
return panes == null ? 0 : panes.length;
}
});
}
/**
* Toggles the bold attribute.
*
* @param e the action event
*/
public void actionPerformed(ActionEvent e) {
JEditorPane editor = getEditor(e);
if (editor != null) {
StyledEditorKit kit = getStyledEditorKit(editor);
MutableAttributeSet attr = kit.getInputAttributes();
boolean bold = (StyleConstants.isBold(attr)) ? false : true;
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setBold(sas, bold);
setCharacterAttributes(editor, sas, false);
}
}
private JEditorPane[] getPanes() {
return Mutex.EVENT.readAccess(new Mutex.Action<JEditorPane[]>() {
public JEditorPane[] run() {
return edit.getOpenedPanes();
}
});
}
public ToggleDebuggingAction(JEditorPane pane) {
this();
assert (pane != null);
this.pane = pane;
actions.add(this);
updateState();
}