StyledDocument

Hi,

I have a StyledDocument doc. I would Like to get local style{font,color,size,b,i,u} of where ever the caret is.

I tried the following:

added a caretlistener to the doc

publicvoid caretUpdate(CaretEvent e)

{

System.out.println("dot="+e.getDot());

System.out.println("mark="+e.getMark());

System.out.println("attributes="+textPane.getStyledDocument().getLogicalStyle(e.getDot()));

}

Even though I have typed in many lines and different fonts, colors,and sizes...

I always get the same output which doesn't match any styles I have made.

[805 byte] By [forumusera] at [2007-10-3 6:17:27]
# 1
Maybe something like this:AttributeSet attributes = textPane.getCharacterAttributes();System.out.println( attributes.containsAttribute(StyleConstants.Bold, Boolean.TRUE) );
camickra at 2007-7-15 1:02:09 > top of Java-index,Desktop,Core GUI APIs...
# 2

Looking at the StyledDocument api I would start with:

Element element = styledDoc.getCharacterElement(pos);

Style style = element.getAttributes();

// retrieve the attributes

See the discussion about logical styles on this page [url=http://javaalmanac.com/egs/javax.swing.text/style_SetPara.html]Retaining the Logical Style When Setting a New Paragraph Style[/url]

and then [url=http://javaalmanac.com/egs/javax.swing.text/style_ListAttr.html?l=rel]Listing the Attributes in a Style[/url] for retrieving the attribute information.

74philipa at 2007-7-15 1:02:09 > top of Java-index,Desktop,Core GUI APIs...
# 3

Thanks... I can now see a list of attributes in a local style.

Element element = styledDoc.getCharacterElement(e.getDot());

SimpleAttributeSet style = new SimpleAttributeSet(element.getAttributes());

System.out.println("style="+style);

outputs this:

style:=foreground=java.awt.Color[r=255,g=153,b=204] family=Century bold=true size=40

However, I am unable to extract single attributes from the "style".

System.out.println("attribute(family)="+style.getAttribute("family"));

outputs: attribute(family)=null

:(

forumusera at 2007-7-15 1:02:09 > top of Java-index,Desktop,Core GUI APIs...
# 4

import java.awt.*;

import java.awt.event.*;

import java.io.IOException;

import java.net.URL;

import java.util.Enumeration;

import javax.swing.*;

import javax.swing.text.*;

public class StyleAttributes implements ActionListener {

//////// Code below copied from TextSamplerDemo.java////////

//////// found on How to Use Editor Panes and Text Panes ////////

//////// at http://java.sun.com/docs/books/tutorial/////////

////////uiswing/components/editorpane.html////////

JTextPane textPane;

private String newline = "\n";

protected static final String buttonString = "JButton";

private JScrollPane getContent() {

//Create a text pane.

textPane = createTextPane();

JScrollPane paneScrollPane = new JScrollPane(textPane);

paneScrollPane.setVerticalScrollBarPolicy(

JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

paneScrollPane.setPreferredSize(new Dimension(250, 155));

paneScrollPane.setMinimumSize(new Dimension(10, 10));

return paneScrollPane;

}

private JTextPane createTextPane() {

String[] initString =

{ "This is an editable JTextPane, ",//regular

"another ",//italic

"styled ",//bold

"text ", //small

"component, ",//large

"which supports embedded components..." + newline,//regular

" " + newline,//button

"...and embedded icons..." + newline, //regular

" ",//icon

newline + "JTextPane is a subclass of JEditorPane that " +

"uses a StyledEditorKit and StyledDocument, and provides " +

"cover methods for interacting with those objects."

};

String[] initStyles =

{ "regular", "italic", "bold", "small", "large",

"regular", "button", "regular", "icon",

"regular"

};

JTextPane textPane = new JTextPane();

StyledDocument doc = textPane.getStyledDocument();

addStylesToDocument(doc);

try {

for (int i=0; i < initString.length; i++) {

doc.insertString(doc.getLength(), initString[i],

doc.getStyle(initStyles[i]));

}

} catch (BadLocationException ble) {

System.err.println("Couldn't insert initial text into text pane.");

}

return textPane;

}

protected void addStylesToDocument(StyledDocument doc) {

//Initialize some styles.

Style def = StyleContext.getDefaultStyleContext().

getStyle(StyleContext.DEFAULT_STYLE);

Style regular = doc.addStyle("regular", def);

StyleConstants.setFontFamily(def, "SansSerif");

Style s = doc.addStyle("italic", regular);

StyleConstants.setItalic(s, true);

s = doc.addStyle("bold", regular);

StyleConstants.setBold(s, true);

s = doc.addStyle("small", regular);

StyleConstants.setFontSize(s, 10);

s = doc.addStyle("large", regular);

StyleConstants.setFontSize(s, 16);

s = doc.addStyle("icon", regular);

StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);

ImageIcon pigIcon = createImageIcon("tutorial/images/Pig.gif",

"a cute pig");

if (pigIcon != null) {

StyleConstants.setIcon(s, pigIcon);

}

s = doc.addStyle("button", regular);

StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);

ImageIcon soundIcon = createImageIcon("tutorial/images/sound.gif",

"sound icon");

JButton button = new JButton();

if (soundIcon != null) {

button.setIcon(soundIcon);

} else {

button.setText("BEEP");

}

button.setCursor(Cursor.getDefaultCursor());

button.setMargin(new Insets(0,0,0,0));

button.setActionCommand(buttonString);

button.addActionListener(this);

StyleConstants.setComponent(s, button);

}

/** Returns an ImageIcon, or null if the path was invalid. */

protected static ImageIcon createImageIcon(String path,

String description) {

java.net.URL imgURL = TextSamplerDemo.class.getResource(path);

if (imgURL != null) {

return new ImageIcon(imgURL, description);

} else {

System.err.println("Couldn't find file: " + path);

return null;

}

}

public void actionPerformed(ActionEvent e) {

String ac = e.getActionCommand();

if (buttonString.equals(ac))

Toolkit.getDefaultToolkit().beep();

//////// End code copied from TextSamplerDemo.java ////////

// Show attributes at the current position of caret.

if(ac.equals("show local")) {

int pos = textPane.getCaretPosition();

StyledDocument doc = textPane.getStyledDocument();

Element element = doc.getCharacterElement(pos);

AttributeSet attrs = element.getAttributes();

String name = element.getName();

showElementAttributes(attrs, name, pos);

}

// Show attributes of all styles in textPane.

if(ac.equals("all styles"))

showTextPaneStyles();

}

private void showElementAttributes(AttributeSet attrs, String id, int pos) {

System.out.printf("Element %s at pos = %d attribute count = %d%n",

id, pos, attrs.getAttributeCount());

Enumeration e = attrs.getAttributeNames();

while(e.hasMoreElements()) {

Object key = e.nextElement();

Object value = attrs.getAttribute(key);

System.out.printf("\tAttribute: key=%s value=%s%n", key, value);

}

System.out.println("--");

}

//////// Code copied from////////

////////Listing the Styles Associated with a JTextPane ////////

//////// at http://javaalmanac.com/egs/javax.swing.text/////////

////////style_ListStyles.html?l=rel////////

private void showTextPaneStyles() {

DefaultStyledDocument doc = (DefaultStyledDocument)textPane.getDocument();

Enumeration e = doc.getStyleNames();

System.out.println("==== All Styles in textPane ====");

while (e.hasMoreElements()) {

String styleName = (String)e.nextElement();

System.out.printf("styleName = %s%n", styleName);

// Get style object

Style style = doc.getStyle(styleName);

showAttributes(style);

}

System.out.println("========");

}

//////// Code copied from ////////

////////Listing the Attributes in a Style////////

//////// at http://javaalmanac.com/egs/javax.swing.text/ ////////

////////style_ListAttr.html?l=rel ////////

private void showAttributes(Style style) {

// Get number of attributes

int count = style.getAttributeCount();

System.out.println("attribute count = " + count);

// Get enumeration of attribute names; an attribute name can be

// either a string or a StyleConstants object.

Enumeration e = style.getAttributeNames();

while (e.hasMoreElements()) {

Object o = e.nextElement();

if (o instanceof String) {

String attrName = (String)o;

Object attrValue = style.getAttribute(attrName);

System.out.printf("\tAttribute: name=%s value=%s%n",

attrName, attrValue);

} else if (o == StyleConstants.NameAttribute) {

// Retrieve the style's name

String styleName = (String)style.getAttribute(o);

System.out.printf("\tNameAttribute: %s%n", styleName);

} else if (o == StyleConstants.ResolveAttribute) {

// Retrieve the style's parent

Style parent = (Style)style.getAttribute(o);

System.out.printf("\tResolveAttribute: %s%n", parent.getName());

} else {

// Retrieve the style constant name and value

String attrName = o.toString();

Object attrValue = style.getAttribute(o);

System.out.printf("\tStyleConstants: name=%s value=%s%n",

attrName, attrValue);

}

}

}

private JPanel getControl() {

JButton local = new JButton("attributes at caret");

JButton styles = new JButton("all styles");

local.setActionCommand("show local");

styles.setActionCommand("all styles");

local.addActionListener(this);

styles.addActionListener(this);

JPanel panel = new JPanel();

panel.add(local);

panel.add(styles);

return panel;

}

public static void main(String[] args) {

StyleAttributes sa = new StyleAttributes();

JFrame f = new JFrame();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.getContentPane().add(sa.getContent());

f.getContentPane().add(sa.getControl(), "Last");

f.setSize(400,400);

f.setLocation(200,200);

f.setVisible(true);

}

}

74philipa at 2007-7-15 1:02:09 > top of Java-index,Desktop,Core GUI APIs...