Dynamic styles in JTextPane

I am implementing a client which has to print text whose style depends on the strings it receives from the server. I initially implemented different styles, one for each colour I had to support; but what if I want to use a particular colour in addiction to a particular font type (i.e. bold)? Is there a way to retrieve the style currently used and dinamically modify its parameters at runtime? If I can't do this with JTextPane, what should I use instead?
One last question: Is it possible to use a justfied allignment with JTextPane?
Thanks for your attention.

Thanks for the answer, but I'm not sure I've understood what you've said.
Did you try creating a "bold" style and applying both the color and bold style to the same text?I've created a bold style and color styles, but how can I apply two or more styles at once? I'm using the following appendText method to insert a new string into the jTextPane:
public void appendText(String msg, String style) {
        msg = msg + "\n";
        javax.swing.text.Document doc = areaTesto.getStyledDocument();
        try {
        doc.insertString(doc.getLength(), msg, areaTesto.getStyle(style));
        } catch(javax.swing.text.BadLocationException ble) {
            JOptionPane.showMessageDialog(this, "Errore nell'aggiornamento del testo", "Errore", JOptionPane.ERROR_MESSAGE);
        areaTesto.setCaretPosition(doc.getLength());
    }Given this, how can I implement your suggestion?
As it should be clear by now I'm not comfortable with styles, documents and attributes, so please be as clear and simple as possible in your explanation.
Thank you again.

Similar Messages

  • Dynamic style with non spatial data?

    Hi all,
    Here is the situation : I have two spatial tables with attributes.
    Each row in the first one will be affected to a row or several rows in the second using a third table that links the primary keys of both tables. (the third table is actually a temporary table loaded from an xml file)
    I would like to represent that on the map using a dynamic style. My column on which is based the affectation is varchar2 column. So I can't use numeric buckets.
    Is it possible to do that? And how?
    Thank you for your help.
    Max

    Hi Max,
    for varchar2 columns you can use Collection bucket styles where the values can numbers of strings. Post the general sturcture of each table (the attributes), and how you would like to link them. You may be able to define a view linking the tables, and then use one attribute of the view for the collection style.
    Joao

  • Implementing Dynamic Styles for Popups based on Query

    I have a page with multiple report regions which are individually displayed depending upon values assigned to variables via a search page. On the resulting report region, I display the results of my SQL query as text, text fields, select lists, textarea, and popups. These fields are editable and will be submitted to update the data displayed and stored in the database. To maintain database referential integrity, obviously some fields will be reuired and some will have default values. I want to visually emphasize these two characteristics to the user by changing the field background color and font color depending upon whether the element is required or whether a default value is being displayed.
    I have tried to accomplish as much as possible via inline styling and can accomplish everything except the popups. If I hard-code the style values for the popup IDs, I can affect the styles. The problem is that the number of rows which need to be addressed is dependent upon the number of rows in my table. Popup IDs are indexed by the row number (e.g. f01_0001 is the ID for the popup field for row 1; f01_0002 is the ID for the popup field for row 2, etc). Changing the template would affect all popups and I only want to address specific ones. I have tried to implement a JavaScript function (FORMAT_DEFAULT_AND_REQUIRED_COLUMNS(formItem1,formItem2,formItem3)) on the page HTML Header section which is called by onload="jvascript:FORMAT_DEFAULT_AND_REQUIRED_COLUMNS('P30_DATA_TYPE','P30_VIEW_OR_EDIT','P30_SOURCE');" from the "On Load - Page HTML Body Attribute."
    Basically, I want this function to execute each time the page is loaded to dynamically assign style values to the popups (and potentially other columns as well). Depending upon the values of the three formItems, the function would know which column tags would need to be affected. From within the JavaScript function, I would call:
    document.getElementById(f01tag).style.setExpression("background-color", "blue", "JavaScript");
    This would occur within a loop from 1 to the number of rows to be displayed on the report region and the f01tag would be incremented by the loop counter.
    Any ideas, assistance, or direction would be greatly appreciated. Thank you.

    Ed
    Taken a look at it using the developer access you provided. Think you were nearly there!
    The style sheet wasn't being picked up because of the link href in the page template. Think you must have cut and pasted the existing link for the theme CSS and left in the themes/theme_10/ component? That would apply for style sheets stored there in the file system. For your ApEx CSS from the database you just need #WORKSPACE_IMAGES#pdam.css.
    To get the styles defined in the CSS appearing for all of the items - including the popups - I added class="default|required|default_required" attributes using the p_attributes parameter in the APEX_ITEM package methods referenced in your report source query. (Probably possible to do this in the Tabular Form Element section of the report definition too, but if you've got dynamic requirements as to which classes are needed where, the former approach is more likely to be useful - you can control which classes using DECODE, CASE, scalar subqueries etc.)
    Seems to be working in Windows IE 5.5/6/7 and Opera 9; Mac Firefox 2 and Safari 3 beta. Safari 2 doesn't support styling of the select lists, as I mentioned in my previous post.
    Few points on your CSS:
    1. Setting font size in pixels causes accessibility issues, both due to Win IE lacking support for user resizing of pixel sized text, and because of general variation in display resolutions. Use a different method for real world use.
    2. Always specify a generic font family as a fallback in case your preferred fonts are not available: font-family: "Times New Roman", Times, serif;
    3. text-shadow is not yet a widely supported CSS 3 property. Although it is working in Safari 3 - even (to my surprise!) in a form control - it looks kind of unreadable, and I doubt that even when widely available it will be universally supported for forms controls. Anyway, note that text-shadow properties are not specified enclosed in quotes.
    Hope this lets you progress.

  • Dynamic style selection in smartform depending on language

    Hi
    Today I assign a style to a smartform statically in form attributes. I don't assign styles to any subnodes.
    Is it possible to make the assignment of style to the smartform dynamically at runtime?
    (If you can suggest a completely other solution for my problem, that will also be very much appreciated).
    Reason: I have a requirement to translate a lot of smartform (maybe 100+) from English to Chinese, Japanese, Korean, Russian etc.
    I'm in a Unicode environment and the translation itself seems to work quit simple.
    But there seems to be a major problem about the font.
    In our smartforms we use smartstyles with 2 fonts helve and times.
    So far we have just translated a few smartforms to Chinese with SE63. We have also translated some material texts and addresses and we have defined a test printer with CNSAPWIN.
    Test prints now shows that we can print all the Chinese texts, but all the texts and numbers that is not translated into Chinese (i.e. quantity, price, net value etc.) is printed with a bigger font size.
    Now this is a know problem discussed in more forum threads and OSS nodes, and the solution seems to be, to change the style to use special Chinese fonts and adjust the font size.
    We have tested this at it seems to solve the problem. But all the threads and notes discussing this issue is talking about "the English smartform" and u201Cthe Chinese smartform" and so on. This is not very smart.
    If we follow this strategy and creates a form for each special language (special from our perspective), we will need 5 different versions of every smartform and the time needed for future maintenance will increase dramatically.
    A much better solution would be to have one smartform that is translated with SE63 and only make 5 different styles to handle the different fonts etc. This solution requires however that we can assign the styles to the smartforms dynamically at runtime.
    Yours sincerely / Med venlig hilsen / 此致敬礼 / Mit freundlichen Grüßen / Pozdrawiam
    Thomas Madsen Nielsen

    Hi!
    In SAPScript there is an option for this, using the STYLE keyword. However I don't know will it work in Smartforms or not.
    If it is not working, I think you have to different character and paragraph formats within 1 smartstyle for each language.
    About the STYLE keyword:
    Changing the Style: STYLE Locate the document in its SAP Library structure
    The STYLE control command allows you to change the style within a text. The new style is in force until another STYLE command is issued. If you specify * as the name of the style, then the system reverts to the default paragraph of the original style or form.
    Syntax:
    /: STYLE style
    /: STYLE *
    A style set with this command has no effect in a text included with INCLUDE. The system takes the paragraph and character formats from the calling text. To use the style set with STYLE in the INCLUDE text as well, you must add DOMINANT to the command.
    Note
    If the INCLUDE text has a style assigned to it, in both cases, the system always takes the paragraph and character formats from the directly assigned style.
    Regards
    Tamá

  • Exchanging Data with Styles in JTextPane

    Is there any way to exchange data between two JTextPanes via a single object? (e.g., extracting Strings or byte[]s which contain both textual data and the corresponding Styles?)
    Thank you!
    Brad

    Thank you again for your suggestions.
    I have previously considered this later approach as well. However, I have no need to load the entirety of a JTextPane --- rather, only small, formatted portions. Moreover, while saving the data from one JTextPane to disk and then reading only the desired portion may seem to be a viable option, the frequency at which I hope to perform these transfers may be too great than to be effective and/or practical. Thus it would be ideal to excerpt/copy portions of JTextPane via an RTF or equivalently-encoded data model; a simple one-to-one process.
    I do appreciate the thoughts you've suggested; please send anything else you think might work.
    Thank you!
    Brad

  • Need help: Saving CCS styles from JTextPane/HTMLDocument?

    I guess topics like this one have been discussed a lot of times here, but I did not find a fitting solution for my source code.
    The idea about my program is to build a JTextPane editor which handles HTML and CCS styles including save- and open-operations for documents. Therefore, I build in the main part of my code an instance of StyleSheet, add some rules to it and transmit it to a HTMLEditorKit. The editor kit is afterwards used to create HTMLDocument instances.
    The problem is the following: When the documents shall be stored, only HTML code (no CSS) is written to output, although my JTextPane displays all styles correctly.
    In my example code, I use the standard output stream to demonstrate the problem without storing any files (see line with ek.write(System.out, doc, 0, doc.getLength()); ).
    What do I have to do that my program even writes CCS-code? And would I have to read files in the same way? If anyone can correct/complete my source code for the given problem, I would be very grateful!!
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import java.awt.*;
    public class Forum1 extends JFrame {
        static final String CSS_RULE =
            "BODY {" +
            " color: #666666;" +
            " background-color: #FFDDDD;" +
            " font-family: Arial, sans-serif;" +
            " font-size: 40;" +
            " margin: 5px 10px 10px 5px;" +
        String text = "Hello <B>World!</B>";
        JTextPane editor;
        public Forum1() {
            // just some properties for this frame
            JPanel contentPane = (JPanel) getContentPane();
            contentPane.setLayout(new BorderLayout());
            setSize(new Dimension(640, 500));
            // building html-textpane with some styles
            editor = new JTextPane();
            editor.setContentType("text/html");
            StyleSheet ss = new StyleSheet();
            ss.addRule(CSS_RULE);
            HTMLEditorKit ek = new HTMLEditorKit();
            ek.setStyleSheet(ss);
            HTMLDocument doc = (HTMLDocument) ek.createDefaultDocument();
            editor.setDocument(doc);
            editor.setText(text);
            // print contents to standard output
            try {
                ek.write(System.out, doc, 0, doc.getLength());
            catch (Exception e) {
                e.printStackTrace();
            contentPane.add(editor, BorderLayout.CENTER);
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.
                                                 getSystemLookAndFeelClassName());
                    catch (Exception exception) {
                        exception.printStackTrace();
                    Forum1 f = new Forum1();
                    f.setVisible(true);
    }(Note: this is a part of a bigger source, but it is mostly reduced to the point of my question).
    Thank you,
    Hewi :-)

    really no-one? :-(

  • Problems with dynamic resize of JTextPane...

    Dear Java Gurus,
    I am quite new to Java, so I am strill struggling to understand the details about it all...but thanks
    to a lot of very helpful people in this forum, the bits and pieces start to come together, even
    though it's obvious that I now need guidance again :-)
    I posted yesterday regarding how I could implement a JTextPane that dynamically would change
    its height. This means that the JTextPane has a fixed width, but when the user types in text, its sets
    its own height to fit the enterred text. A very kind person posted some code that more or less looks
    like the code below, with a few changes:
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.awt.*;
    public class test {   
      public static void main(String[] argv)
        final JFrame frame = new JFrame();           
        JTextPane pane= new JTextPane("Test ");           
        pane.getDocument().addDocumentListener(new DocumentListener()
          public void insertUpdate(DocumentEvent e) {proccess(e.getDocument());}         
          public void removeUpdate(DocumentEvent e) {proccess(e.getDocument());}         
          public void changedUpdate(DocumentEvent e) {proccess(e.getDocument());}   
          private void proccess(Document doc)
            Dimension size = pane.getPreferredSize();     
            pane.setSize(150, (int)size.getHeight());    
            frame.validate();    
        frame.getContentPane().add(new JScrollPane(pane), BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      
        frame.setSize(400, 300);       
        frame.setLocationRelativeTo(null);       
        frame.setVisible(true);   
    }The code works just fine, but has a small "feature" in it that I don't understand. It appears
    like the resizing has a delay in it. If you enter the JTextPane and press return once, the text
    pane will not resize. If you press backspace, the cursor will move back up, but now the
    text pane will increase its size, to fit the size of the previos text size. If you now press the
    return key again, the text pane shrinks by one line.
    In other words...it seems the resizing is always delayed by one, as if the last entered
    character is not taken into account when preferredSize() returns the value. As I don't yet
    understand in which order events are generated and handled, does anybody see what I
    need to change in order to get rid of this slightly disturbing delay? :-)
    Any comments would be highly appreciated!
    Best regards,
    Xxodus.

    You try to ask size before edition process is complete.
    Try to change size after finishing processing of document change event.
    Like this.
          private void proccess(Document doc)
              SwingUtilities.invokeLater(new Runnable() {
                  public void run() {
                      Dimension size = pane.getPreferredSize();
                      pane.setSize(150, (int)size.getHeight());
                      frame.validate();
          }regards,
    Stas

  • Creating a dynamic style font with live cycle desginer ES 8.2

    Can I control dynamicly the style (Italic) and the weight (bold) of  text in a  dynamic pdf form ( imade it with livecycle designer ES 8.2) that gets its  data from an XMl file.

    Hi,
    A lot of the information you need is in Adobe's scripting guide http://www.adobe.com/go/learn_lc_scriptingReference  Also there is a very useful Adobe guide to Calculations and Scripts (and while it is for version 6 it is still very good because of the way it is laid out) http://partners.adobe.com/public/developer/en/tips/CalcScripts.pdf
    The Javascript could be used in the Layout: Ready event.
    For italic font:
    if (...some test...)
         this.font.posture = "italic";
    else
         this.font.posture = "normal";
    For bold font:
    if (...some test...)
         this.font.weight = "bold";
    else
         this.font.weight = "normal";
    The script will change the font for the complete field. I don't think you can change parts of a field.You can also change font colour and font type (the guides above will help).
    Good luck,
    Niall

  • How to change dynamically style in smartforms

    Dear All,
              I had a requirnment to select different styles in smartforms depending on some condition, can u plz suggest me any solution for this.Thanking you.
    With best regards
    Gaurav Lashkari

    Hi,
    Goto Transaction smartform.
    Place radio button on style, then give <b>style name</b> and
    create it.
    In paragraph format right click and create node.
    Give some name it wil create a node.
    Double click on that node than u can
    change your style by using font tab.
    You can create any number of node.
    Save and activate.
    Then in your smartform->form attributes->output options
    Give your <b>style name</b>.
    Then place the cursor on the text to be modified and
    select your style from paragraph format.
    Thanks.

  • JDBC theme - dynamic advanced style

    Hi
    I'm using dynamic JDBC theme's from within javascript. For instance :
    themebasedfoi=new MVThemeBasedFOI("XX","<themes><theme name='XX'><jdbc_query asis='true' spatial_column='GEOLOC' jdbc_srid='82343' render_style='DK_VALUE' datasource='PHV_MAP'>"+aip_sql+"</jdbc_query></theme></themes>");
    that works nicely.
    Now I want to be able to build the advanced bucket style on the fly instead of using a fixed advanced style(in the example DK_VALUE').
    I can define the style as for instance:
    vol_style="<style name='vol_style'><AdvancedStyle><BucketStyle><Buckets><RangedBucket seq='0' label='less than 100k' high='10000.0' style='C.RED_1'/><RangedBucket seq='1' label='100k - 150k' low='10000.0' high='15000.0' style='C.YEL_1'/><RangedBucket seq='2' label='150k - 250k' low='15000.0' high='20000.0' style='C.BLUE_1'/><RangedBucket seq='3' label='250k - 350k' low='20000.0' high='30000.0' style='C.GRE_1'/><RangedBucket seq='4' label='350k - 450k' low='30000.0' high='100000.0' style='C.GRE_2'/></Buckets></BucketStyle></AdvancedStyle></style>";
    But how can I get the dynamic theme to use this dynamically created advanced style?
    Jesper

    With MapViewer 11 preview 1, you can define dynamic styles and use the dynamic styles in your jdbc themes. We provide classes such as MVStyleColor, MVStyleMarker, MVBucketStyle, MVBarCharStyle, MVPieCharStyle and the most generalized all, MVXMLStyle to define any MapViewer supported style.
    Here is an example.
    var dynStyle = new MVStyleColor("mycolor", "00FF00", "FF0000") ;
    var themeDef =
    '<theme name="mytheme" >' +
    '<jdbc_query spatial_column="geometry" jdbc_srid="8307" ' +
    'render_style="mycolor" datasource="mvdemo">'+
    'select geometry from counties' +
    '</jdbc_query></theme>' ;
    var themeBasedFOI = new MVThemeBasedFOI('county_theme', themeDef);
    themeBasedFOI.addStyle(dynStyle) ;
    mapview.addThemeBasedFOI(themeBasedFOI);

  • Setting font style on hover for spark datagrid

    I'm trying to skin a Spark datagrid. I have most things sorted by creating a custom skin, but one thing I can't find is how to set the colour of the row's font on hover. I can set the background colour fine, but how would I go about changing the font colour when a user hovers over the row?
    Thanks

    Hi
    You don’t actually deal with the text that’s displayed in the a datagrid inside of the skin
    Look at item renderers for the grid columns. You can style your text or whatever else you would like to display in the grid, in the renderer
    Hope that helps a little
    If you are still stuck just let me know and I’ll send you some code
    Cheers
    g
    heres some code
    NOTE: I am making this up as I sit here so I may be forgetting something. Don’t be surprised if this doesn’t work, but the basic idea is right I think
    So in the spark datagrid when you set your column (if you use mxml) this will replace a glob renderer so you can have a different one for each column if you wish.
    <s:GridColumn dataField="Status"
    headerText="name"
    width="37"                                                    
    itemRenderer="fooRenderer"
    />
    Or set a gloabel renderer in the grid def itself
    <s:DataGrid itemRenderer=”fooRenderer” />
    Then write a custom renderer: fooRenderer.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:GridItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
                         xmlns:s="library://ns.adobe.com/flex/spark"
                         xmlns:mx="library://ns.adobe.com/flex/mx"
                         clipAndEnableScrolling="true"
                         >
           <fx:Script>
                  <![CDATA[
                         override public function discard(willBeRecycled:Boolean):void
                               labelData.text="";
                               super.discard(willBeRecycled);
                         override public function prepare(hasBeenRecycled:Boolean):void
                               if(data)
                                       // set the colour of the text label to black
                                      labelData.setStyle("color",0x000000)
                                      // put some logic here to dynamic style the label
                               //check for the 'format' function on the column  (THIS MAY BE WRONG)
                               if( column.labelFunction != null )
                                      labelData.text = column.labelFunction( data, column );
                               else
                                      labelData.text = data[column.dataField];
                         super.prepare(hasBeenRecycled);
                  ]]>
           </fx:Script>
           <s:Label id="labelData" />
    </s:GridItemRenderer

  • Possible to change style of predefined theme ?

    Using Java API - is it possible to dynamically change style of a predefined theme ?

    There is no API method that allows you to change the predefined theme styling rules definition. In your request you can create dynamic styles and also dynamic themes that uses these dynamic styles.

  • How to listen and obtain caret positions of changed text in JTextPane?

    Hi,
    I have a JTextPane that displays text with some styles on particular words in the text. For example, I highlight words with red color if they are in my dictionary file. I use regular expression to find matches, replace them with their corresponded definitions, and call setCharacterAttributes to add styles to the definitions. I store all start and end caret positions of the matched words/definitions in a vector. So, I can redisplay styles of all previous matches.
    The problem is that I'd like to be able to edit the text of some previous matches. So, with those changes all caret positions that I already store in the vector need to be updated.
    How can I obtain caret positions of changed text in JTextPane?
    How can I know that a user is currently changing text in the JTextPane?
    How can I get style of text such as color that is being changed?
    Thank you very much.

    Thank you very much, camickr, for your reply.
    I think that I might not know the right way to handle JTextPane and Document object.
    What I have done are:
    - Add style to JTextPane using, for example,
    Style targetCurrentMatchStyle = this.targetWindowTextPane.addStyle("Red", null);
    StyleConstants.setForeground(targetCurrentMatchStyle, Color.red);//For highlight - Then, I use regular expression (Pattern and Matcher) to find a match in text. For each match, I get start and end position from matcher.start() and matcher.end().
    if(matcher.find(start)){
    String term=matcher.group();
    int start=matcher.start();
    int end = matcher.end();
    //find definition for the matched term.
    String definition=mydictionaryHash.get(term);
    //Store caret positions in lists
    startPositionList.add(start);
    matchedLength=lengthList.add(definition.length());
    //Add changed to text in textpane
    StringBuffer sb=new StringBuffer();
    matcher.appendReplacement(sb, definition);
    matcher.appendTail(sb);
    //Get translated text from StringBuffer after replacement
    String translatedText=sb.toString();
    targetWindoTextPane.setText(translatedText);
    //Update start position for next search
    start=start+definition.length();
    //Add style to matched regions below.
    }- From the lists of start positions and matched lengths, I use the following code to add "Red" color to the matched text regions including all previously matched.
    for(int i=0;i<startPositionList.size();i++){
    this.targetWindowTextPane.getStyledDocument().setCharacterAttributes(
    startPositionList.get(i),
    lengthList.get(i),
    this.targetWindowTextPane.getStyle("Red"),
    true);
    }My issue is that I'd like to be able edit previously matched regions and update all positions of the matched regions stored in the lists.

  • Compiled Style Sheets: Unable to Compile with ClassReferences

    My CSS compiles fine in the project, but will not build a
    separate swf in the IDE or from the commandline.
    Here is a snippet of code from the CSS:
    selectedUpSkin : ClassReference('ui.skins.SelectedNavSkin');
    Here is the error from the IDE:
    1120: Access of undefined property SelectedNavSkin.
    Here is the error when trying from the command line:
    Error: Access of undefined property SelectedNavSkin.
    selectedUpSkin : ClassReference('ui.skins.SelectedNavSkin');

    Greg that could be, what I ended up doing is just moving all
    the styles that reference the custom class back into the main
    embedded style sheet, then I compile the "dynamic" style sheet
    separately.
    This works, but I would still be interested in know *why* I
    can do what I outlined above.

  • Style Sheets & templates enquiry

    I am only just getting into using Style Sheets but am not sure if I can assign a particular location & width to a paragraph, which, if changed, will change all documents using it?
    Is there a way to create a dynamic template in InDesign which is referenced/ linked to all the documents based on it?
    Thanks

    There is no dynamic styles (like CSS) in InDesign, but you can use Book feature for synchronizing styles between documents.
    You can´t define size or location parameters of a column with paragraph style, with object styles you can define fixed width of column if it helps.....

Maybe you are looking for

  • How to find imei number

    hi my name is james bowd and i was wondering how to find my imei number/code as i need prof that the iphone is mine please reply on [email protected] thank you

  • Asset under construction

    Hi Guru,            I want to know about how the internal order is the linked to asset under construction?

  • I bought a WD Caviar Green today

    Now I have one WD10EADS 1TB HDD (linked by Firewire 400/800 dock, but my Mac is 400 only) and one Hitachi 159GB HDD(USB 2.0 direct link). I partition WD off into two partitions with GUID? I hope I didn't do anything wrong? 'cause there are 3 options,

  • HT203180 Is there a way to revert this process?

    I noticed that when i create a new version it makes the file larger in size taking up more space. So can i make it so it isnt an ipad or ipod version again to get the lower gb back?

  • Library/Containers

    Hi I am in the process of consolodating and crosschecking backup data (migrating from one NAS to a different NAS system), the data had been copied down to local external drives ( why = nas was suspect, so I wanted to get the data out in the shortest