下面列出了怎么用javax.swing.JTextPane的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Create a new InformationPanel.
*/
InformationPanel() {
setLayout(new OverlayLayout(this));
JComponent container = SBoxLayout.createContainer(SBoxLayout.VERTICAL);
glassPane = new JComponent(){};
add(glassPane);
add(container);
// ** Zone name **
nameField = new JTextPane();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
nameField.setAlignmentX(CENTER_ALIGNMENT);
nameField.setOpaque(true);
nameField.setBackground(getBackground());
nameField.setForeground(Color.WHITE);
nameField.setFocusable(false);
nameField.setEditable(false);
container.add(nameField, SLayout.EXPAND_X);
// ** Danger display **
dangerIndicator = new DangerIndicator(MAX_SKULLS);
dangerIndicator.setAlignmentX(CENTER_ALIGNMENT);
container.add(dangerIndicator);
// Default to safe, so that we always have a tooltip
describeDanger(0);
}
/**
* Replace text.
*
* @param localNewText New text.
* @param localElement Element.
* @param localTextPane Text Pane.
*/
private void replace(
String localNewText,
Element localElement,
JTextPane localTextPane) {
if ((localElement == null) ||
(localTextPane == null) ||
(localNewText == null)) {
return;
}
// Initialize
int startOffset = MWPaneFormatter.getUUIDStartOffset(localTextPane, localElement);
int endOffset = MWPaneFormatter.getUUIDEndOffet(localTextPane, localElement);
// Replace
try {
localTextPane.getDocument().remove(startOffset, endOffset - startOffset);
localTextPane.getDocument().insertString(startOffset, localNewText, localElement.getAttributes());
localTextPane.setCaretPosition(startOffset);
localTextPane.moveCaretPosition(startOffset + localNewText.length());
} catch (BadLocationException e1) {
// Nothing to be done
}
}
public static void vpcsRegister(LinkList first, String fileCurrentpath, NodeShow nodeView
, JTextPane rightBotJTextPane) {
if(null== hallKeeper) {
hallKeeper= new ConcurrentHashMap<>();
}
if(200> hallKeeper.size()) {
try {
BootNeroDoc bootNeroDoc= new BootNeroDoc(first, fileCurrentpath, nodeView, rightBotJTextPane);
Sets.register(bootNeroDoc.getId());//sets ��sleeper����ʱ��������Է�����������ݡ�
Pillow.register(bootNeroDoc);//pillow����Щ���ݵķ���洢��
Vision.registerVision(bootNeroDoc);//vision��sleeper���еľ����ξ���
hallKeeper.put(bootNeroDoc.getId(), bootNeroDoc);
bootNeroDoc.start();
}catch(Exception e) {
Skivvy.working(hallKeeper, e);//skivvy����vision�� pillow��sets��sleeper ȫ�̹���ͷ�����
}
}
}
SelectConfigDialog() {
super(null, false, false);
setTitle("Run Configuration");
myPanel = new JPanel();
myTextPane = new JTextPane();
Messages.installHyperlinkSupport(myTextPane);
String selectConfig = "<html><body>" +
"<p>The run configuration for the Flutter module must be selected." +
"<p>Please change the run configuration to the one created when the<br>" +
"module was created. See <a href=\"" +
FlutterConstants.URL_RUN_AND_DEBUG +
"\">the Flutter documentation</a> for more information.</body></html>";
myTextPane.setText(selectConfig);
myPanel.add(myTextPane);
init();
//noinspection ConstantConditions
getButton(getCancelAction()).setVisible(false);
}
/**
* Creates new form WikiEditPanel
*/
public WikiEditPanel(String wikiLanguage, boolean editing, boolean switchable) {
this.wikiLanguage = wikiLanguage;
this.switchable = switchable;
this.wikiFormatText = "";
this.htmlFormatText = "";
initComponents();
pnlButtons.setVisible(switchable);
textCode.getDocument().addDocumentListener(new RevalidatingListener());
textPreview.getDocument().addDocumentListener(new RevalidatingListener());
textCode.addCaretListener(new CaretListener() {
@Override
public void caretUpdate(CaretEvent e) {
makeCaretVisible(textCode);
}
});
textCode.getDocument().addDocumentListener(new EnablingListener());
// A11Y - Issues 163597 and 163598
UIUtils.fixFocusTraversalKeys(textCode);
UIUtils.issue163946Hack(scrollCode);
Spellchecker.register(textCode);
textPreview.putClientProperty(JTextPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
setEditing(editing);
}
public static void main(String[] args)
{
JFrame frame = new JFrame("LineNumberDemo");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
JPanel panel = new JPanel();
frame.setContentPane( panel );
panel.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
panel.setLayout(new BorderLayout());
JTextPane textPane = new JTextPane();
textPane.setFont( new Font("monospaced", Font.PLAIN, 12) );
textPane.setText("abc");
JScrollPane scrollPane = new JScrollPane(textPane);
panel.add(scrollPane);
scrollPane.setPreferredSize(new Dimension(300, 250));
LineNumber lineNumber = new LineNumber( textPane );
scrollPane.setRowHeaderView( lineNumber );
frame.pack();
frame.setVisible(true);
}
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);
}
}
SelectConfigDialog() {
super(null, false, false);
setTitle("Run Configuration");
myPanel = new JPanel();
myTextPane = new JTextPane();
Messages.installHyperlinkSupport(myTextPane);
String selectConfig = "<html><body>" +
"<p>The run configuration for the Flutter module must be selected." +
"<p>Please change the run configuration to the one created when the<br>" +
"module was created. See <a href=\"" +
FlutterConstants.URL_RUN_AND_DEBUG +
"\">the Flutter documentation</a> for more information.</body></html>";
myTextPane.setText(selectConfig);
myPanel.add(myTextPane);
init();
//noinspection ConstantConditions
getButton(getCancelAction()).setVisible(false);
}
/** Utility method to open a file */
private void openFile(File file) {
Doc doc = (Doc) openDocs.get(file);
if (doc == null) {
doc = new Doc(file);
JTextPane pane = doc.getTextPane();
if (pane != null) {
//otherwise there was an exception
pane.addFocusListener(this);
synchronized (getTreeLock()) {
Component c = documentTabs.add(new JScrollPane(pane));
openDocs.put(file, doc);
documentTabs.setTitleAt(documentTabs.getTabCount()-1, doc.getTitle());
documentTabs.setToolTipTextAt(documentTabs.getTabCount()-1, file.toString());
pane.requestFocus();
documentTabs.setSelectedComponent(c);
}
}
} else {
doc.getTextPane().requestFocus();
}
}
private static JTextPane createInfoPanel(String notification) {
JTextPane balloon = new JTextPane();
balloon.setContentType("text/html");
String text = getDetails(notification).replaceAll("(\r\n|\n|\r)", "<br>");
balloon.setText(text);
balloon.setOpaque(false);
balloon.setEditable(false);
balloon.setBorder(new EmptyBorder(0, 0, 0, 0));
if (UIManager.getLookAndFeel().getID().equals("Nimbus")) {
//#134837
//http://forums.java.net/jive/thread.jspa?messageID=283882
balloon.setBackground(new Color(0, 0, 0, 0));
}
balloon.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
URLDisplayer.getDefault().showURL(e.getURL());
}
}
});
return balloon;
}
private void printHeaders(JTextPane pane, JSONObject headers,
StyledDocument doc, Style boldStyle, Style defaultStyle) throws BadLocationException {
assert headers != null;
Set keys = new TreeSet(new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return ((String)o1).compareToIgnoreCase((String)o2);
}
});
keys.addAll(headers.keySet());
for (Object oo : keys) {
String key = (String)oo;
doc.insertString(doc.getLength(), key+": ", boldStyle);
String value = (String)headers.get(key);
doc.insertString(doc.getLength(), value+"\n", defaultStyle);
}
}
@Override
protected void initStylesForTextPane(final JTextPane textPane, int mainTextSize) {
textPane.setContentType("text/html");
final HTMLDocument doc = (HTMLDocument) textPane.getDocument();
final StyleSheet css = doc.getStyleSheet();
/*
* Configure standard styles
*/
css.addRule("body { font-family: Dialog; font-size: " + (mainTextSize + 1)
+ "pt }");
css.addRule("a { color: blue; font-style: italic }");
css.addRule("._timestamp { color: " + colorToRGB(HEADER_COLOR)
+ "; font-size: " + (mainTextSize - 1)
+ "pt; font-style: italic }");
css.addRule("._header { color: " + colorToRGB(HEADER_COLOR) + " }");
/*
* Configure notification types
*/
for (final NotificationType type : NotificationType.values()) {
final Color color = type.getColor();
if (color != null) {
css.addRule("." + type.getMnemonic() + " { color: "
+ colorToRGB(color) + "; font-weight: bold; }");
}
}
}
public TwoWaySerialComm2(JTextPane txt_area)// , JSObject win)
{
t_area = txt_area;
this.doc = t_area.getStyledDocument();
this.style = t_area.addStyle("Red", null);
StyleConstants.setForeground(this.style, Color.black);
}
public void init(Object[][] tableData_old,JTextPane text){
try {
this.text= text;
this.tableData_old= tableData_old;
CreatMap();
} catch (IOException e) {
e.printStackTrace();
}
Registrar();
this.resize(w,h);
}
public static void insertNewLine(JTextPane textPane) {
StyledDocument document = (StyledDocument)textPane.getDocument();
try {
String styleName = "stylenewline";
document.insertString(document.getLength(), "\n", document.getStyle(styleName));
} catch (BadLocationException e) {
throw new IllegalStateException(e);
}
}
void showInfo()
{
final JTextPane html = new JTextPane();
html.setContentType("text/html");
html.setEditable(false);
html.setText(Util.getSystemInfo());
final JScrollPane scroll = new JScrollPane(html);
scroll.setPreferredSize(new Dimension(420, 300));
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run()
{
final JViewport vp = scroll.getViewport();
if (vp != null) {
vp.setViewPosition(new Point(0, 0));
scroll.setViewport(vp);
}
}
});
JOptionPane.showMessageDialog(frame, scroll, "Framework info",
JOptionPane.INFORMATION_MESSAGE, null);
}
public
void setTextPane(JTextPane textpane) {
this.textpane=textpane;
textpane.setEditable(false);
textpane.setBackground(Color.lightGray);
this.doc=textpane.getStyledDocument();
}
/**
* Maps {@code JTextPane.setLogicalStyle(Style)} through queue
*/
public void setLogicalStyle(final Style style) {
runMapping(new MapVoidAction("setLogicalStyle") {
@Override
public void map() {
((JTextPane) getSource()).setLogicalStyle(style);
}
});
}
private void createComponents() {
text = new JTextPane();
text.setEditable(false);
text.setFocusable(false);
nextMessage = new JTextField(10);
// when enter is pressed, send the message
final Insets inset = new Insets(3, 3, 3, 3);
save = new JButton(saveAction);
save.setMargin(inset);
save.setFocusable(false);
for (final GamePlayer gamePlayer : data.getPlayerList().getPlayers()) {
Optional.ofNullable(frame.getUiContext().getFlagImageFactory().getSmallFlag(gamePlayer))
.ifPresent(image -> iconMap.put(gamePlayer, new ImageIcon(image)));
}
}
private Window createAttributeDialog(Model model, String attributeName, String label) {
JDialog window = new JDialog((Window) null, model.getAddress() + ": " + attributeName, ModalityType.MODELESS);
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JLabel(label), BorderLayout.NORTH);
// TODO make this a JsonField...
JTextPane pane = new JTextPane();
pane.setContentType("text/html");
pane.setText(JsonPrettyPrinter.prettyPrint(JSON.toJson(model.get(attributeName))));
ListenerRegistration l = model.addListener((event) -> {
if(event.getPropertyName().equals(attributeName)) {
// TODO set background green and slowly fade out
pane.setText(JsonPrettyPrinter.prettyPrint(JSON.toJson(event.getNewValue())));
}
});
panel.add(pane, BorderLayout.CENTER);
window.addWindowListener(new WindowAdapter() {
/* (non-Javadoc)
* @see java.awt.event.WindowAdapter#windowClosed(java.awt.event.WindowEvent)
*/
@Override
public void windowClosed(WindowEvent e) {
l.remove();
attributeWindows.remove(model.getAddress() + ":" + attributeName);
}
});
return window;
}
public ROCViewer(AreaUnderCurve auc) {
setLayout(new BorderLayout());
String message = auc.toString();
criterionName = auc.getName();
// info string
JPanel infoPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
infoPanel.setOpaque(true);
infoPanel.setBackground(Colors.WHITE);
JTextPane infoText = new JTextPane();
infoText.setEditable(false);
infoText.setBackground(infoPanel.getBackground());
infoText.setFont(infoText.getFont().deriveFont(Font.BOLD));
infoText.setText(message);
infoPanel.add(infoText);
add(infoPanel, BorderLayout.NORTH);
// plot panel
plotter = new ROCChartPlotter();
plotter.addROCData("ROC", auc.getRocData());
JPanel innerPanel = new JPanel(new BorderLayout());
innerPanel.add(plotter, BorderLayout.CENTER);
innerPanel.setBorder(BorderFactory.createMatteBorder(5, 0, 10, 10, Colors.WHITE));
add(innerPanel, BorderLayout.CENTER);
}
public ReloadDependencies(JTextPane textPanel) {
this.textPanel = textPanel;
dto = CentralLookup.getDefLookup().lookup(EGTaskDataObjectDataObject.class);
if(dto!=null) {
egtask = dto.getEgtask();
}else{
egtask = null;
}
parse = new ParseDependencies();
vioGenQueriesGenerator = new GenerateVioGenQueries();
}
private void setupTextPane(final JTextPane textPane, String comment) {
if( UIUtils.isNimbus() ) {
textPane.setUI( new BasicTextPaneUI() );
}
textPane.setText(comment);
Caret caret = textPane.getCaret();
if (caret instanceof DefaultCaret) {
((DefaultCaret)caret).setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
}
// attachments
if (!attachmentIds.isEmpty()) {
AttachmentHyperlinkSupport.Attachement a = AttachmentHyperlinkSupport.findAttachment(comment, attachmentIds);
if (a != null) {
String attachmentId = a.id;
if (attachmentId != null) {
int index = attachmentIds.indexOf(attachmentId);
if (index != -1) {
BugzillaIssue.Attachment attachment = attachments.get(index);
AttachmentLink attachmentLink = new AttachmentLink(attachment);
HyperlinkSupport.getInstance().registerLink(textPane, new int[] {a.idx1, a.idx2}, attachmentLink);
} else {
Bugzilla.LOG.log(Level.WARNING, "couldn''t find attachment id in: {0}", comment); // NOI18N
}
}
}
}
// pop-ups
textPane.setComponentPopupMenu(commentsPopup);
textPane.setBackground(blueBackground);
textPane.setBorder(BorderFactory.createEmptyBorder(3,3,3,3));
textPane.setEditable(false);
textPane.getAccessibleContext().setAccessibleName(NbBundle.getMessage(CommentsPanel.class, "CommentsPanel.textPane.AccessibleContext.accessibleName")); // NOI18N
textPane.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(CommentsPanel.class, "CommentsPanel.textPane.AccessibleContext.accessibleDescription")); // NOI18N
}
/**
* Maps {@code JTextPane.insertIcon(Icon)} through queue
*/
public void insertIcon(final Icon icon) {
runMapping(new MapVoidAction("insertIcon") {
@Override
public void map() {
((JTextPane) getSource()).insertIcon(icon);
}
});
}
public JComponent createComponent() {
JPanel panel = new JPanel();
JPanel console = new JPanel();
panel.setLayout(new BorderLayout());
final JEditorPane text = new JTextPane();
text.setMargin(new Insets(8, 8, 8, 8));
text.setCaretColor(new Color(0xa4, 0x00, 0x00));
text.setBackground(new Color(0xf2, 0xf2, 0xf2));
text.setForeground(new Color(0xa4, 0x00, 0x00));
Font font = findFont("Monospaced", Font.PLAIN, 14, new String[]{
"Monaco", "Andale Mono"});
text.setFont(font);
JScrollPane pane = new JScrollPane();
pane.setViewportView(text);
pane.setBorder(BorderFactory.createLineBorder(Color.darkGray));
panel.add(pane, BorderLayout.CENTER);
console.validate();
final TextAreaReadline tar = new TextAreaReadline(text,
getString("Wellcom") + " \n\n");
RubyInstanceConfig config = new RubyInstanceConfig() {
{
//setInput(tar.getInputStream());
//setOutput(new PrintStream(tar.getOutputStream()));
//setError(new PrintStream(tar.getOutputStream()));
setObjectSpaceEnabled(false);
}
};
Ruby runtime = Ruby.newInstance(config);
tar.hookIntoRuntimeWithStreams(runtime);
run(runtime);
return panel;
}
@Override
protected JComponent getTextComponent(String locator) throws Exception {
JTextPane textComponent = new JTextPane();
textComponent.setText(getContent(locator));
textComponent.setFont(new Font("monospaced", Font.PLAIN, 12));
textComponent.setEditable(false);
textComponent.setCaretPosition(0);
textComponent.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
return textComponent;
}
/**
* Creates the customization panel.
*
* @param typeName the type name
* @return the j panel
*/
private JPanel createCustomizationPanel(String typeName) {
this.currentTypeName = typeName;
String defaultAnnotStyleName = CAS.TYPE_NAME_ANNOTATION;
Style defaultAnnotStyle = this.styleMap.get(defaultAnnotStyleName);
GridLayout layout = new GridLayout(0, 1);
JPanel topPanel = new JPanel(layout);
this.textPane = new JTextPane();
Style style = this.styleMap.get(typeName);
if (style == null) {
style = defaultAnnotStyle;
}
Style defaultStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
this.textPane.addStyle(defaultStyleName, defaultStyle);
setCurrentStyle(style);
this.fgColor = StyleConstants.getForeground(this.currentStyle);
this.bgColor = StyleConstants.getBackground(this.currentStyle);
this.fgIcon = new ColorIcon(this.fgColor);
this.bgIcon = new ColorIcon(this.bgColor);
topPanel.add(createColorPanel("Foreground: ", this.fgIcon, FG));
topPanel.add(createColorPanel("Background: ", this.bgIcon, BG));
setTextPane();
topPanel.add(this.textPane);
JPanel buttonPanel = new JPanel();
createButtonPanel(buttonPanel);
topPanel.add(buttonPanel);
return topPanel;
}
/** Creates new form AddPropertyDialog */
public AddPropertyDialog(NbMavenProjectImpl prj, String goalsText) {
initComponents();
manager = new ExplorerManager();
//project can be null when invoked from Tools/Options
project = prj;
okbutton = new JButton(NbBundle.getMessage(AddPropertyDialog.class, "BTN_OK"));
manager.setRootContext(Node.EMPTY);
tpDesc.setEditorKit(new HTMLEditorKit());
tpDesc.putClientProperty( JTextPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE );
manager.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
Node[] nds = getExplorerManager().getSelectedNodes();
if (nds.length != 1) {
okbutton.setEnabled(false);
} else {
PluginIndexManager.ParameterDetail plg = nds[0].getLookup().lookup(PluginIndexManager.ParameterDetail.class);
if (plg != null) {
okbutton.setEnabled(true);
tpDesc.setText(plg.getHtmlDetails(false));
} else {
okbutton.setEnabled(false);
tpDesc.setText("");
}
}
}
});
((BeanTreeView)tvExpressions).setRootVisible(false);
((BeanTreeView)tvExpressions).setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.goalsText = goalsText;
RequestProcessor.getDefault().post(new Loader());
}
/**
* Maps {@code JTextPane.getInputAttributes()} through queue
*/
public MutableAttributeSet getInputAttributes() {
return (runMapping(new MapAction<MutableAttributeSet>("getInputAttributes") {
@Override
public MutableAttributeSet map() {
return ((JTextPane) getSource()).getInputAttributes();
}
}));
}
public void subtituteImagesInTextPane(JTextPane textPane, String text) {
JTextPaneMapper textPaneMapper = new JTextPaneMapper(textPane, imageInfoReader);
String changedText = text;
for(Entry<String, ImageIds> mapping : getTextToImageMapping().entrySet()) {
changedText = tooltipImages.substituteImages(changedText, mapping.getKey(), mapping.getValue(), textPaneMapper::addImage);
}
textPaneMapper.addText(changedText);
}