How to give styles to my HTMLDocument inside a JTextPane?

I have a JTextPane with a HTMLDocument attached to it. How can I style the text which is typed in? For example I want to set a larger font. How can I do this in my example?
Another problem is that when I hit the alignment buttons the text is actually aligned according to the hit button but the JEditorPane doesn't show the text correctly. It also doesn't enter a line feed when typing ENTER key.
Can someone help me on this please?
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
public class AdditionalText extends JFrame implements ActionListener {
     private JButton leftAlign;
     private JButton centerAlign;
     private JButton rightAlign;
     private JTextPane editor;
     private JButton save;
     private JButton dump;
     public AdditionalText() {
          setTitle("Test Frame");
          JPanel topToolbar = new JPanel();
          leftAlign = new JButton("Left");
          centerAlign = new JButton("Center");
          rightAlign = new JButton("Right");
          ActionListener alignLeft = new HTMLEditorKit.AlignmentAction("alignLeft", 0);
          ActionListener alignCenter = new HTMLEditorKit.AlignmentAction("alignCenter", 1);
          ActionListener alignRight = new HTMLEditorKit.AlignmentAction("alignRight", 2);
          leftAlign.addActionListener(alignLeft);
          centerAlign.addActionListener(alignCenter);
          rightAlign.addActionListener(alignRight);
          topToolbar.add(leftAlign);
          topToolbar.add(centerAlign);
          topToolbar.add(rightAlign);
          editor = createEditor();
          JPanel bottomToolbar = new JPanel();
          save = new JButton("Save");
          save.addActionListener(this);
          dump = new JButton("Dump");
          dump.addActionListener(this);
          bottomToolbar.add(save);
          bottomToolbar.add(dump);
          getContentPane().add(BorderLayout.NORTH, topToolbar);
          getContentPane().add(BorderLayout.CENTER, editor);
          getContentPane().add(BorderLayout.SOUTH, bottomToolbar);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          setSize(new Dimension(640, 480));
          setLocation((screenSize.width - 640) / 2, (screenSize.height - 480) / 2);
     private JTextPane createEditor() {
          JTextPane textPane = new JTextPane() {
               public void paintComponent(Graphics g) {
                    Graphics2D g2 = (Graphics2D) g;
                    g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
                    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
                    g2.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
                    g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
                    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                    g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
                    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                    super.paintComponent(g2);
          textPane.setEditorKit(new HTMLEditorKit());
          return textPane;
     public void actionPerformed(ActionEvent e) {
          HTMLDocument htmlDocument = (HTMLDocument) editor.getDocument();
          if(e.getSource() == save) {
               HTMLEditorKit kit = (HTMLEditorKit)editor.getEditorKitForContentType("text/html");
               try {
                    kit.write(System.out, htmlDocument, 0, htmlDocument.getLength());
               } catch (IOException ex) {
                    ex.printStackTrace();
               } catch (BadLocationException ex) {
                    ex.printStackTrace();
          } else if(e.getSource() == dump) {
               htmlDocument.dump(System.err);
     public static void main(String[] args) {
          try {
               UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          } catch (ClassNotFoundException e) {
               e.printStackTrace();
          } catch (InstantiationException e) {
               e.printStackTrace();
          } catch (IllegalAccessException e) {
               e.printStackTrace();
          } catch (UnsupportedLookAndFeelException e) {
               e.printStackTrace();
          AdditionalText at = new AdditionalText();
          at.show();
}

I created a class that can be used to highlight Java source code. Most of the code is for handling multi line comments. If you just want it to highlight certain keywords then you can get rid of all that logic. In case your interested, the code can be downloaded from here:
http://www.discoverteenergy.com/files/SyntaxDocument.java

Similar Messages

  • Css styles donot work well inside headers

    I have placed some content inside the header tags.If i apply css styles to the content inside the tags means,the header comes down.what can i do for this?
    CSS styles:
    header
    min-height: 120px;
    background: #9EA5CF;
    #maintitle {
        color: #FFF;
        padding-left: 50px;
        padding-top: -20px;
    HTML Code:
    <header>
      <h1 id="maintitle">LORUM IPSUM</h1>
    </header>

    Murray, on the second part of your post (default margins), I think that is the case when I use images as the target for a live link (in IE) ... I have to go in and set the 'border' to 0.
    Actually, a simple rule for this in all browsers is -
    a img { border:none; }
    That will prevent any image that is also a link from having a border. And it's definitely not just in IE.
    On the first part, all I know is when I first started doing some naming of IDs and Classes, my computer told me not to go there, so I don't.
    Now, that could easily be because I had no clue what was really going on.
    I prefer to think of it as your just being new to CSS, but yes - that's most likely it. Can you give us a specific example?
    HTML4 or HTML5 should not affect how you USE your CSS.

  • How to give backgound color

    H All :
    I am using collection in my application for textbox
    HTMLDB_ITEM.TEXT(2,null,30,500,''style="background-color: RED"'')
    i am using this which give me the red in color background effect
    i am using
    HTMLDB_ITEM.DISPLAY_AND_SAVE(2,null,30,500)
    how to give a background or a fore ground color this item
    please suggest
    Thanks
    Sudhir

    It's actually quite easy.
    What you have to do is write a custom tree cell renderer which extends DefaultTreeCellRenderer. In that class, your getTreeCellRenderer() method should do something like the following:
    public Component getTreeCellRendererComponent(
        JTree tree, Object value, boolean selected,
        boolean expanded, boolean leaf, int row, boolean hasFocus )
            Component treeCellRenderer =
                  super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
            if (selected) {
                setForeground(Color.WHITE);
                setBackground(BACKGROUND_SELECTION_COLOR);
            } else {
                treeCellRenderer.setForeground(Color.RED);
            return treeCellRenderer;
    Then you'll need to make sure that you call myTree.setCellRenderer(new CustomTreeCellRenderer());
    cheers,
    Greg

  • How to give Username and password when calling HTTP page?

    I have this code when i run this I get credentials error. How to give credentials .The authentication is set to windows in the https page. Means pop up will appear to get the credentials
    declare
    req UTL_HTTP.REQ;
    resp UTL_HTTP.RESP;
    value varchar2(1024);
    p_url varchar2(4000);
    OPT varchar2(1000);
    BEGIN
    dbms_output.put_line('');
    p_url:='http://www.xyz.com/';
    dbms_output.put_line(p_url);
    req := UTL_HTTP.begin_REQUEST(p_url);
    utl_http.set_header(req, 'User-Agent', 'Mozilla/4.0');
    resp := utl_http.get_response(req);
    loop
    utl_http.read_line(resp, value, true);
    dbms_output.put_line(value);
    end loop;
    exception
    when utl_http.end_of_body then
    utl_http.end_response(resp);
    END;
    When i run this i get
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
    <title>401 - Unauthorized: Access is denied due to invalid credentials.</title>
    <style type="text/css">

    Basic authentication is set using the UTL_HTTP.Set_Authentication() call.
    If you are using a proxy and need procy authentication, you can set the username and password for proxy access, as part of the proxy URL. E.g.
    utl_http.set_proxy( 'http://proxyuser:[email protected]', null );NTLM (Windows NT LAN Manager) authentication is proprietary and not part of the HTTP specifications. If that is needed, try and use the username and password as part of the URL - or do some research on how to manually perform NTLM authentication.
    If you are using HTTPS, you need an Oracle Wallet with that server's certificate (making it a trusted certificate), and then set/use the wallet using the UTL_HTTP.Set_Wallet() call. See sample code in {message:id=10820182}.

  • [Question]how to count the occurance of numbers inside the array

    im just practicing my java skill but i cant get my program work can you give me guys some idea on how to determine a number that occured more than 1 inside the array e.g i have 10 elements and inside of my offset i have
    1,2,5,4,5,6,5,8,9,5
    and what im planning to do is count the occurances of the number who occures more than 1 and for that 5 occur 3 times how my program can know that i use for loop but cant figure out how to filter the occurances of numbers inside
    my offset
    thank's

    Encephalopathic you said put - 1 instead i did - 2
    public class sample
       public static void main(String args[])
          int num[] = {2,2,2};
          int index1, count = 0, find = 0;
          for(index1 = 0; index1 < num.length - 2; index1++)
             for(int index2 = 0; index2 < num.length; index2++)
                if(num[index2]==num[index1])
                  find = num[index2];
                  count++;
             System.out.println("i found " + find + " " + count + " same number inside your offset");
    }output is:
    i found 2 3 same number inside your offset
    but another question is what if i want my program to tell the other number that occur 1 time
    like this:
    i found 1 2 same number inside your offset
    i found 2 0 same number inside your offset
    i found 1 2 same number inside your offset

  • How to give Authorization?

    I have created a 'Z' application which consists of create, change and display User interface.Whenever the user selects craete all fields go editable, change will have some fields editable and display all uneditable.I used only one view and i handled all three modes using invisible and enable property.
    Now i want to allow only certain users to access create and change but display for all users.How to give this kind of autorization in webdynpro????
    Please explain me about authorization in webdynpro taking my scenario?

    Hello,
    I hope you are aware of authority checks in ABAP in general. In your scenario, what you can do is: create one context attribute IS_AUTHORIZED of type WDY_BOOLEAN.
    And in WDDOINIT of the component controller or view controller,
    do the authorization check using AUTHORITY-CHECK stmt and if the check fails i.e. sy-subrc is not equals to 0, then
    set the attribute  IS_AUTHORIZED to false. Otherwise set it to true.
    And you have to bind the enabled property of the buttons to this context attribute IS_AUTHORIZED.
    Please refer to the following code sample:
        DATA lo_nd_selection_type TYPE REF TO if_wd_context_node.
        DATA lo_el_selection_type TYPE REF TO if_wd_context_element.
        lo_nd_selection_type = wd_context->get_child_node( name = wd_this->wdctx_flex_config ).
        lo_el_selection_type = lo_nd_selection_type->get_element( ).
      AUTHORITY-CHECK OBJECT <objectName>
      ID <name1> FIELD <f1>
      ID <name2> FIELD <f2>.
      IF sy-subrc <> 0.
    * Prohibhit the user from modifying config
        lo_el_selection_type->set_attribute(
          name =  `IS_AUTHORIZED`
          value = abap_false ).
      ELSE.
        lo_el_selection_type->set_attribute(
          name =  `IS_AUTHORIZED`
          value = abap_true ).
      ENDIF.
    Hope this helps!
    Regards,
    Srilatha

  • How to give the no of lines per a page in alv report

    hi
    could u plz inform me
    how to give the no of lines per page in alv report
    in ordinary report we can give line-count na
    how can we give in alvs.
    thanx
    kals.

    Hi Kalyan,
    There is another Forum(Abap Development) where u can post abap related stuffs and u can also get quick answers there..
    Cheers...
    Santosh

  • How to give no of lines per page in alv report

    hi
    could anybody tell me
    how to give no of lines per page in alv report
    i need bottom of page too
    if possible plz send the code too
    it ll be very helpful to me
    thanx
    kals.

    Hi,
    This is possible, using some of the events in the ALV.
    You could use AFTER_LINE_OUTPUT event and call you form after say, a certain line count is reached on the list output.
      MOVE 'AFTER_LINE_OUTPUT' TO gw_event-name.
      MOVE 'AFTER_LINE_OUTPUT' TO gw_event-form.
      APPEND gw_event TO gt_events.
      CALL FUNCTION 'REUSE_ALV_LIST_DISPLAY'
           EXPORTING
                it_events                = gt_events[]
    and define the form for each event as follows - this would be a dynamic call by the ALV.
    *&      Form  after_line_output
    *       Form for the After Line Output Event in the internal table
    *      --> rs_lineinfo
    FORM after_line_output USING rs_lineinfo TYPE slis_lineinfo.
      IF sy-linno eq v_linno.          "Defaulted value for line count
        perform write_footer.
        NEW-PAGE.
      ENDIF.
    ENDFORM.                    " after_line_output
    For lines per page:
    rs_lineinfo-tabindex would give you the index of the current line in the list, which you could use to read the t_outtab table, and reduce the line count of items displayed on the earlier page.
    There are a few other events too, like BEFORE_LINE_OUTPUT and END_OF_LIST which you can use as required and print the data.
    Regards,
    Anil.

  • How to give constant space in sap scripts.

    Dear experts,
    In my requirement I am printing invoice line item details. In my program,I am printing 8 columns. How to give the constant space in my output.
    My issue.: here am fetching Internal Excise Document Number (DOCNO) item number (zeile) plant (werks) quantity (menge) storage location (lgort) and so on.
    when i am fetching the values from the table, the values are different from each and every rows. so nothing would be aligned properly into the column. For example, if the  doc no is having 10 char,from item no all the values of the column is getting moved to right side. in my second row doc no is having only 2 chars. in this case every column value is moving left side. its looking like realigned and not good.
    How do i give constant space for each and every column. so if the values are more or less it could not be moved to any side.
    please hellp me to solve this issue.
    <MOVED BY MODERATOR TO THE CORRECT FORUM>
    Thanks in advance.
    Regards,
    Sandy.
    Edited by: Alvaro Tejada Galindo on Sep 28, 2011 3:40 PM

    Hi,
    check out ur tab positioning in paragraph format...any misalignment is their or not.
    second thing you can do is checkout your printer i.e zebra printer or .matrix etc. your using sometimes misalignment happens
    in printer..or print some sample values for verifying the root cause .
    regards,
    KRISHNA

  • How to give a message in the UI page if there is an error in AppImpl method

    How to give an error message in the jsf page if the AppImpl method fails ?
    Use case : I have a create form and a submit button which binds with a client interface method in Application Impl class. If the method fails due to some exception , how can I notify the users with proper error message ?
    Thanks
    Suneesh

    Hi,
    As the previous reply (casting the result) is the best solution here (separating model and view logic) but sometimes we do a shortcut.
    may be it is not the best approach but it comes handy most of the time, this approach is also error-proven. we used it more than 2 years in large applications.
    add the following code whenever you want to add message in UI be aware that we have add it in a jar and add that library to the model projects
    FacesContext ctx = getFacesContext();
    FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, "");
    ctx.addMessage(null, fm);
    you just need to add jsf library to the model applications and replace msg with your message.
    regarding throw jboException, it seems good most of the time but sometimes when you are in middle of the transaction it somehow ruin the flow of the transactions.
    Regards.

  • How to give ** bydefault in password in module pool screen .

    Hi experts
    how to give  *******  by default in password in module pool screen .
    Thanks

    Hi ,
        Double click on the field u will get a pop up window
        i.e. attribute window for that field.
        in that window you have a tab called Program at the bottom.
       in program tab you have many checkboxes.
      check the check box with name *Entry.
      and activate.
    what ever you enter now will be in password formate
    Regards
    Ajay

  • How to give error message for the screen element text field when wrong i/p

    How to give error message for the screen element text field when wrong i/p
    when wrong input given
    eg. 
    I have a text box with SBOOK-CARRID
    so when user give wrong entry in text box i.e LG
    then I should give some error stating that the the input is invalid or not available ,
    now it showing the error of standard messages,
    i want manual message to be displayed when error comes.
    Thank you,
    Regards,
    Jagrut Bharatkumar Shukla

    Hi all,
    Thank you for your valuable reply,
    but the thing is that its a screen field,
    i.e text box not a selection screen
    i created in screen layout
    with name sbook-carrid
    now i want to get error message display if wrong i/p is given
    thank you.
    Regards,
    Jagrut bharatkumar Shukla,

  • How to give other material as a free good

    Hi all,
    Here i am getting doubt how to give free good for one material to another material. for ex:- if customer buy product A he will get product B as a free good how do we configure in to sap. i tried in exclusive method in the sales order it is executing and when coming to delivery and billing free good line item is not getting in deliveries and billing how to do this. plz tell the required steps to do this.
    Thanks & Regards,
    kishore

    Hi,
    This can be done in two ways.
    1)Create a BOM with the product A as the header material.Make sure that the sub items are for free of cost.Pricing will be done only for this header.
    2)Mainatin the different item category for both material A and material B.
    Goto VOV7 T.Code.
    Select material B's item category.
    Details.
    Maintain the pricing as "B".
    Save.
    Regards,
    Krishna.

  • How to give connection between sap R/3 to sap BI 7.0 system

    how to give connection between sap R/3 to sap BI 7.0 system

    Hello,
    Check this links:
    http://help.sap.com/bp_biv135/BBLibrary/documentation/B84_BB_ConfigGuide_EN_DE.doc
    You can look at:
    OSS Note 184971 'Notes on BW source system connections' and http://help.sap.com/saphelp_nw04/helpdata/en/80/1a61e5e07211d2acb80000e829fbfe/content.htm
    You can use this best practice connectivity guide for connecting BW to any SAP source system . It explains step by step procedure to connect the source systems to BW.
    http://help.sap.com/bp_biv135/BBLibrary/documentation/B84_BB_ConfigGuide_EN_DE.doc
    http://help.sap.com/saphelp_nw2004s/helpdata/en/ac/4a4e38493e4774e10000009b38f889/frameset.htm
    http://help.sap.com/bestpractices/crossindustry/businessintelligence/v131/BBLibrary/documentation/B84_BB_ConfigGuide_EN_DE.doc
    check this:
    http://wiki.ittoolbox.com//index.php/HOWTO%3ARe%2DConnect%5FR/3%5Fand%5FBW#Type_Transaction_SM59._Maintain_RFC_destinations
    Regards,
    Jorge Diogo

  • How to give dynamic file path in the selection  screen

    Hi All,
    How to give dynamic file path f4 functionality to user on the selection so that he can browse for the path in the presentation serve? I believe there is one fun module is there for this purpose I am not getting that
    Please help me in this regard.
    Thanks&Regards
    Mahesh

    HI,
    check this program.
    <b>report ZWA_TEST2.
    PARAMETERS: a(100) default 'PRESS F4'.
    data: filet type table of FILE_TABLE.
    data: wa type file_table.
    data: count type i.
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR a.
    CALL METHOD CL_GUI_FRONTEND_SERVICES=>FILE_OPEN_DIALOG
      CHANGING
        FILE_TABLE              = filet
        RC                      = count .
    loop at filet into wa.
      a = wa-FILENAME.
    endloop.</b>
    Regards,
    HRA

Maybe you are looking for

  • Freight in STO

    Dear Experts Non valuated material is transferred to another plant via stock transfer order. We have used FRB1 condition in STO with FRE and FR1 keys. In this transaction we want to post freight cost to one of our expense account (GR/IR freight vend

  • Mail constantly re-downloads thousands of IMAP messages

    On my laptop, I have nine IMAP accounts set up. Many of them are very old and have tens of thousands of messages stored in many folders. Mail.app is caching them locally, but frequently it seems to feel the need to re-download many thousands of them.

  • All Labels in the Smartform  should be printed under one spool request ?

    Hi All, I need to print the labels with some data .At a time I have to print 10 labels with the same Spool request. I have required data in one internal table .I am looping the internal table and printing the label.In this case every time control lea

  • Multi-pass isnt working...

    I accuired a multipass for The Daily Show. It's showing new epsiodes at the Daily show web page but I am not quite sure how Itunes updates because it is not downloading the most recent episodes. What can cause this to happen? Is there a certain time

  • Create a new Mail Folder in Outlook 2011 and control its location?

    Hello, I want to create a new mail folder in Outlook in a location of my choosing (from dialogue box) After selecting the location, the user would get a dialog box that asks for the users initials (i.e CY) A second dialog box would ask for the name o