下面列出了怎么用javax.swing.text.html.HTML的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Determines the number of rows occupied by
* the table cell represented by given element.
*/
/*protected*/ int getRowsOccupied(View v) {
// PENDING(prinz) this code should be in the html
// paragraph, but we can't add api to enable it.
AttributeSet a = v.getElement().getAttributes();
String s = (String) a.getAttribute(HTML.Attribute.ROWSPAN);
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
// fall through to one row
}
}
return 1;
}
/**
* Determines the number of rows occupied by
* the table cell represented by given element.
*/
/*protected*/ int getRowsOccupied(View v) {
// PENDING(prinz) this code should be in the html
// paragraph, but we can't add api to enable it.
AttributeSet a = v.getElement().getAttributes();
String s = (String) a.getAttribute(HTML.Attribute.ROWSPAN);
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
// fall through to one row
}
}
return 1;
}
/**
* Determines the number of rows occupied by
* the table cell represented by given element.
*/
/*protected*/ int getRowsOccupied(View v) {
// PENDING(prinz) this code should be in the html
// paragraph, but we can't add api to enable it.
AttributeSet a = v.getElement().getAttributes();
String s = (String) a.getAttribute(HTML.Attribute.ROWSPAN);
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
// fall through to one row
}
}
return 1;
}
/**
* Determines the number of rows occupied by
* the table cell represented by given element.
*/
/*protected*/ int getRowsOccupied(View v) {
// PENDING(prinz) this code should be in the html
// paragraph, but we can't add api to enable it.
AttributeSet a = v.getElement().getAttributes();
String s = (String) a.getAttribute(HTML.Attribute.ROWSPAN);
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
// fall through to one row
}
}
return 1;
}
/**
* The operation to perform when this action is triggered.
*
* @param e the action event
*/
public void actionPerformed(ActionEvent e) {
JTextComponent target = getTextComponent(e);
if ((target != null) && (e != null)) {
String[] temp = res.getImageResourceNames();
Arrays.sort(temp, String.CASE_INSENSITIVE_ORDER);
JComboBox jc = new JComboBox(temp);
final com.codename1.ui.Image img = res.getImage((String)jc.getSelectedItem());
JOptionPane.showMessageDialog(HTMLEditor.this, jc, "Pick", JOptionPane.PLAIN_MESSAGE);
if ((! target.isEditable()) || (! target.isEnabled()) && img != null) {
UIManager.getLookAndFeel().provideErrorFeedback(target);
return;
}
try {
((HTMLEditorKit)wysiwyg.getEditorKit()).insertHTML((HTMLDocument)wysiwyg.getDocument(),
wysiwyg.getCaret().getDot(), "<img width=\"" + img.getWidth() + "\" height=\"" + img.getHeight() + "\" src=\"local://" + jc.getSelectedItem()+ "\" />", 0, 0,
HTML.Tag.IMG);
//target.getDocument().insertString(target.getSelectionStart(), "<img src=\"local://" + jc.getSelectedItem() + "\" />", null);
//target.replaceSelection("<img src=\"local://" + jc.getSelectedItem() + "\" />");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Determines the number of columns occupied by
* the table cell represented by given element.
*/
/*protected*/ int getColumnsOccupied(View v) {
// PENDING(prinz) this code should be in the html
// paragraph, but we can't add api to enable it.
AttributeSet a = v.getElement().getAttributes();
String s = (String) a.getAttribute(HTML.Attribute.COLSPAN);
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
// fall through to one column
}
}
return 1;
}
@Override public void actionPerformed(ActionEvent e) {
textArea.append(String.format("----%n%s%n", getValue(Action.NAME)));
String id = field.getText().trim();
String text = editorPane.getText();
ParserDelegator delegator = new ParserDelegator();
try {
delegator.parse(new StringReader(text), new HTMLEditorKit.ParserCallback() {
@Override public void handleStartTag(HTML.Tag tag, MutableAttributeSet a, int pos) {
Object attrId = a.getAttribute(HTML.Attribute.ID);
textArea.append(String.format("%[email protected]=%s%n", tag, attrId));
if (id.equals(attrId)) {
textArea.append(String.format("found: pos=%d%n", pos));
int endOffs = text.indexOf('>', pos);
textArea.append(String.format("%s%n", text.substring(pos, endOffs + 1)));
}
}
}, Boolean.TRUE);
} catch (IOException ex) {
ex.printStackTrace();
textArea.append(String.format("%s%n", ex.getMessage()));
UIManager.getLookAndFeel().provideErrorFeedback(textArea);
}
}
/** This method analizes the tag t and adds some \n chars and spaces to the
* tmpDocContent.The reason behind is that we need to have a readable form
* for the final document. This method modifies the content of tmpDocContent.
* @param t the Html tag encounted by the HTML parser
*/
protected void customizeAppearanceOfDocumentWithStartTag(HTML.Tag t){
boolean modification = false;
if (HTML.Tag.P == t){
int tmpDocContentSize = tmpDocContent.length();
if ( tmpDocContentSize >= 2 &&
'\n' != tmpDocContent.charAt(tmpDocContentSize - 2)
) { tmpDocContent.append("\n"); modification = true;}
}// End if
if (modification == true){
Long end = new Long (tmpDocContent.length());
Iterator<CustomObject> anIterator = stack.iterator();
while (anIterator.hasNext ()){
// get the object and move to the next one
CustomObject obj = anIterator.next();
// sets its End index
obj.setEnd(end);
}// End while
}//End if
}
/**
* Determines the number of columns occupied by
* the table cell represented by given element.
*/
/*protected*/ int getColumnsOccupied(View v) {
// PENDING(prinz) this code should be in the html
// paragraph, but we can't add api to enable it.
AttributeSet a = v.getElement().getAttributes();
String s = (String) a.getAttribute(HTML.Attribute.COLSPAN);
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
// fall through to one column
}
}
return 1;
}
/**
* Determines the number of rows occupied by
* the table cell represented by given element.
*/
/*protected*/ int getRowsOccupied(View v) {
// PENDING(prinz) this code should be in the html
// paragraph, but we can't add api to enable it.
AttributeSet a = v.getElement().getAttributes();
String s = (String) a.getAttribute(HTML.Attribute.ROWSPAN);
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
// fall through to one row
}
}
return 1;
}
/** This method analizes the tag t and adds some \n chars and spaces to the
* tmpDocContent.The reason behind is that we need to have a readable form
* for the final document. This method modifies the content of tmpDocContent.
* @param t the Html tag encounted by the HTML parser
*/
protected void customizeAppearanceOfDocumentWithSimpleTag(HTML.Tag t){
boolean modification = false;
// if the HTML tag is BR then we add a new line character to the document
if (HTML.Tag.BR == t){
tmpDocContent.append("\n");
modification = true;
}// End if
if (modification == true){
Long end = new Long (tmpDocContent.length());
Iterator<CustomObject> anIterator = stack.iterator();
while (anIterator.hasNext ()){
// get the object and move to the next one
CustomObject obj = anIterator.next();
// sets its End index
obj.setEnd(end);
}// End while
}//End if
}
public @Override void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
if ( t == HTML.Tag.DT ) {
where = IN_DT;
currentDii = null;
}
else if ( t == HTML.Tag.A && where == IN_DT ) {
where = IN_AREF;
Object val = a.getAttribute( HTML.Attribute.HREF );
if ( val != null ) {
hrefVal = val.toString();
currentDii = new DocIndexItem( null, null, contextURL, hrefVal );
}
}
else if ( t == HTML.Tag.A && (where == IN_DESCRIPTION_SUFFIX || where == IN_DESCRIPTION) ) {
// Just ignore
}
else if ( (t == HTML.Tag.B || t == HTML.Tag.SPAN)/* && where == IN_AREF */) {
/*where = IN_AREF;*/
// Ignore formatting
}
else {
where = IN_BALAST;
}
}
/**
* Determines the number of columns occupied by
* the table cell represented by given element.
*/
/*protected*/ int getColumnsOccupied(View v) {
// PENDING(prinz) this code should be in the html
// paragraph, but we can't add api to enable it.
AttributeSet a = v.getElement().getAttributes();
String s = (String) a.getAttribute(HTML.Attribute.COLSPAN);
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
// fall through to one column
}
}
return 1;
}
/**
* Determines the number of columns occupied by
* the table cell represented by given element.
*/
/*protected*/ int getColumnsOccupied(View v) {
// PENDING(prinz) this code should be in the html
// paragraph, but we can't add api to enable it.
AttributeSet a = v.getElement().getAttributes();
String s = (String) a.getAttribute(HTML.Attribute.COLSPAN);
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
// fall through to one column
}
}
return 1;
}
/**
* Determines the number of columns occupied by
* the table cell represented by given element.
*/
/*protected*/ int getColumnsOccupied(View v) {
// PENDING(prinz) this code should be in the html
// paragraph, but we can't add api to enable it.
AttributeSet a = v.getElement().getAttributes();
String s = (String) a.getAttribute(HTML.Attribute.COLSPAN);
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
// fall through to one column
}
}
return 1;
}
/**
* Determines the number of rows occupied by
* the table cell represented by given element.
*/
/*protected*/ int getRowsOccupied(View v) {
// PENDING(prinz) this code should be in the html
// paragraph, but we can't add api to enable it.
AttributeSet a = v.getElement().getAttributes();
String s = (String) a.getAttribute(HTML.Attribute.ROWSPAN);
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
// fall through to one row
}
}
return 1;
}
/**
* Determines the number of rows occupied by
* the table cell represented by given element.
*/
/*protected*/ int getRowsOccupied(View v) {
// PENDING(prinz) this code should be in the html
// paragraph, but we can't add api to enable it.
AttributeSet a = v.getElement().getAttributes();
String s = (String) a.getAttribute(HTML.Attribute.ROWSPAN);
if (s != null) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
// fall through to one row
}
}
return 1;
}
public void setHRef(int pos, Document doc) {
hRef = null;
text = null;
if (!(doc instanceof HTMLDocument)) {
return;
}
HTMLDocument hdoc = (HTMLDocument) doc;
Iterator iterator = hdoc.getIterator(HTML.Tag.A);
while (iterator.isValid()) {
if (pos >= iterator.getStartOffset() && pos < iterator.getEndOffset()) {
AttributeSet attributes = iterator.getAttributes();
if (attributes != null && attributes.getAttribute(HTML.Attribute.HREF) != null) {
try {
text = hdoc.getText(iterator.getStartOffset(), iterator.getEndOffset() - iterator.getStartOffset()).trim();
hRef = attributes.getAttribute(HTML.Attribute.HREF).toString();
setIndexOfHrefAndText(hdoc, pos, text, hRef);
} catch (BadLocationException e) {
e.printStackTrace();
}
return;
}
}
iterator.next();
}
}
private HTML.Tag findTag( final AttributeSet attr ) {
final Enumeration names = attr.getAttributeNames();
while ( names.hasMoreElements() ) {
final Object name = names.nextElement();
final Object o = attr.getAttribute( name );
if ( o instanceof HTML.Tag ) {
if ( HTML.Tag.CONTENT == o ) {
continue;
}
if ( HTML.Tag.COMMENT == o ) {
continue;
}
return (HTML.Tag) o;
}
}
return null;
}
@Override public View create(Element elem) {
View v = super.create(elem);
if (v instanceof LabelView) {
// the javax.swing.text.html.BRView (representing <br> tag) is a
// LabelView but must not be handled
// by a WrapLabelView. As BRView is private, check the html tag from
// elem attribute
Object o = elem.getAttributes().getAttribute(StyleConstants.NameAttribute);
if ((o instanceof HTML.Tag) && o == HTML.Tag.BR) {
return new BRView(elem);
}
}
if (v instanceof InlineView) {
return new WrapInlineView(elem);
} else if (v instanceof ParagraphView) {
return new WrapParagraphView(elem);
}
return v;
}
@Override
public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {
String tag = t.toString();
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "SimpleTag <{0}> with attributes: {1}",
new Object[]{tag, Collections.list(a.getAttributeNames()).toString()});
}
if (readingForm) {
if (TAG_INPUT.equalsIgnoreCase(tag)) {
inputs.add(new SimpleAttributeSet(a));
}
}
}
public void handleSimpleTag(HTML.Tag tag, MutableAttributeSet attributes, int position) {
isTitle = false; // (tag == HTML.Tag.TITLE); // ??
// System.out.println(" "+tag);
if (wantURLS && tag == HTML.Tag.A)
extractHREF(attributes);
}
public TagElement (Element elem, boolean fictional) {
this.elem = elem;
htmlTag = HTML.getTag(elem.getName());
if (htmlTag == null) {
htmlTag = new HTML.UnknownTag(elem.getName());
}
insertedByErrorRecovery = fictional;
}
@Override
public void handleEndTag(HTML.Tag t, int pos) {
if (stringBuilder.length() != 0
&& t.isBlock()
&& !stringBuilder.toString().endsWith(lineBreak)) {
stringBuilder.append(lineBreak);
}
}
/** This method is called when the HTML parser encounts an empty tag
*/
@Override
public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos){
// fire the status listener if the elements processed exceded the rate
if ((++elements % ELEMENTS_RATE) == 0)
fireStatusChangedEvent("Processed elements : " + elements);
// construct a feature map from the attributes list
// these are empty elements
FeatureMap fm = Factory.newFeatureMap();
// take all the attributes an put them into the feature map
if (0 != a.getAttributeCount ()){
// Out.println("HAS attributes = " + a.getAttributeCount ());
Enumeration<?> enumeration = a.getAttributeNames ();
while (enumeration.hasMoreElements ()){
Object attribute = enumeration.nextElement ();
fm.put ( attribute.toString(),(a.getAttribute(attribute)).toString());
}//while
}//if
// create the start index of the annotation
Long startIndex = new Long(tmpDocContent.length());
// initialy the start index is equal with the End index
CustomObject obj = new CustomObject(t.toString(),fm,startIndex,startIndex);
// we add the object directly into the colector
// we don't add it to the stack because this is an empty tag
colector.add(obj);
// Just analize the tag t and add some\n chars and spaces to the
// tmpDocContent.The reason behind is that we need to have a readable form
// for the final document.
customizeAppearanceOfDocumentWithSimpleTag(t);
}
public TagElement (Element elem, boolean fictional) {
this.elem = elem;
htmlTag = HTML.getTag(elem.getName());
if (htmlTag == null) {
htmlTag = new HTML.UnknownTag(elem.getName());
}
insertedByErrorRecovery = fictional;
}
/**
* Creates a generic HTML TagElement class.
*
* @param elem an element
* @param fictional if {@code true} the tag is inserted by error recovery.
*/
public TagElement (Element elem, boolean fictional) {
this.elem = elem;
htmlTag = HTML.getTag(elem.getName());
if (htmlTag == null) {
htmlTag = new HTML.UnknownTag(elem.getName());
}
insertedByErrorRecovery = fictional;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
toolkit.realSync();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
document.insertAfterEnd(document.getElement("ab"), textToInsert);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
});
toolkit.realSync();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Element parent = document.getElement("ab").getParentElement();
int count = parent.getElementCount();
if (count != 2) {
throw new RuntimeException("Test Failed! Unexpected Element count = "+count);
}
Element insertedElement = parent.getElement(count - 1);
if (!HTML.Tag.IMPLIED.toString().equals(insertedElement.getName())) {
throw new RuntimeException("Test Failed! Inserted text is not wrapped by " + HTML.Tag.IMPLIED + " tag");
}
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
toolkit.realSync();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
document.insertAfterEnd(document.getElement("ab"), textToInsert);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
});
toolkit.realSync();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Element parent = document.getElement("ab").getParentElement();
int count = parent.getElementCount();
if (count != 2) {
throw new RuntimeException("Test Failed! Unexpected Element count = "+count);
}
Element insertedElement = parent.getElement(count - 1);
if (!HTML.Tag.IMPLIED.toString().equals(insertedElement.getName())) {
throw new RuntimeException("Test Failed! Inserted text is not wrapped by " + HTML.Tag.IMPLIED + " tag");
}
}
});
}
protected boolean isSupportedBreakFlowTag(AttributeSet attr) {
Object o = attr.getAttribute(StyleConstants.NameAttribute);
if (o instanceof HTML.Tag) {
HTML.Tag tag = (HTML.Tag) o;
if ((tag == HTML.Tag.HTML) || (tag == HTML.Tag.HEAD) || (tag == HTML.Tag.BODY) || (tag == HTML.Tag.HR)) {
return false;
}
return (tag).breaksFlow();
}
return false;
}