How to set Font characteristics on JTEXTPane ?

Hello,
For 5 days, I'm looking for a way to set defaults to a text in a JTextPane. I tried many things, but I always failed.
Here is what I want exactly to do :
Before to display a text in a JTextPane, I want all the text to be in a particular font, with a particular size and various attributes (bold, italic, etc..).
So before I make it visible I does the following (certainly it's wrong) :
void InitialLoad()
        try
     in = new FileInputStream(file);
        //Create the text pane and configure it
        rtf.read(in, lpd, 0);
        TextPane.setDocument(lpd);
    catch (Exception ex)   {System.out.println("Errorr"); };
     TextPane.selectAll();
     TextPane.setCaretPosition( 1);
      String fontName=   "Arial";  
      Action FontFamily = new StyledEditorKit.FontFamilyAction(fontName, fontName);
      FontFamily.actionPerformed(null);
      int fontSize=   12;  // default size
      Action FontSize = new StyledEditorKit.FontSizeAction(""+fontSize, fontSize);
      FontSize.actionPerformed(null);
      Action italic = new StyledEditorKit.ItalicAction();
      italic.actionPerformed(null);   // italic is the default
       TextPane.setVisible(true);
}When I do this, the text display correctly, but not with the Defaults I was expecting.
Of course, I have implemented listener classes : UndoableEditListener, DocumentListener and UndoAction() and RedoAction()
Any help would be very welcome. Thanks for all.

If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.

Similar Messages

  • How to set Font in JEditorPane

    i have problem set Font in JEditorPane.please help how to set Font in JEditorPane.
    My Code,
    JEditorPane view = new JEditorPane();
    view.setEditable(false);
    view.setContentType("text/html");
    JScrollPane scroll = new JScrollPane(view);
    scroll.setMinimumSize(new java.awt.Dimension(50, 50));
    scroll.setPreferredSize(new java.awt.Dimension(450, 300));
    scroll.setAutoscrolls(true);
    scroll.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scroll.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    view.setBorder(null);
    view.setFont(new java.awt.Font("Monospaced", 0, 12));
    view.setDragEnabled(true);
    view.setMargin(new java.awt.Insets(10, 10, 10, 10));
    view.setMinimumSize(new java.awt.Dimension(100, 20));
    view.setPreferredSize(new java.awt.Dimension(450, 300));

    Have a look at SimpleAttributeSet.

  • How to set the size of JTextPane according to the size of text??

    hello
    how can i set the size of JTextPane according to the size of text it would contain in such a way that JTextPane should not have ScrollBar.

    StanislavL wrote:
    width should be defined for your container width. suppose you have a very long row of text. Widht full screen widht it wraps into 2 lines but if you set widht of your window to half screen widht there should be 4 lines.
    But you can use the same code and get preferred widht as well.u mean like this :
    objTextPane.getParent().getWidth();Edited by: 811243 on Sep 6, 2011 5:32 AM

  • How to set font of a row in DataGrid? (FB3)

    I have found examples of how to set the background color of a row based on an attribute of the data item in the row, but I cannot find anything that tells me how to set the font style. Ideally I want to choose either normal or italic based on an attribute which is not displayed in the data grid (as is possible for background color).Can anyone help?
    Thanks

    The first item renderer post on my blog has an example that colors text
    differently.  You can use a similar technique to change the fontStyle

  • How to set font in JTextArea

    There is a function setFont() in class JTextArea, but it seems i only can set "bold","Italic" and "font size", but i want to set something like "Times new roman" and "Courier New"
    who knows how to set?
    //

    If your Java Runtime isn't configured (for whatever reason) to see the fonts you want, setting the font's name might just set it to the default value. Hence it looks like nothing happened.
    To see what fonts are available:String[] fontNames = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
    for (int j=0; j<fontNames.length; j++)
      System.out.println(fontNames[j]);To set a font:String fontname = "Courier New";
    int style = Font.PLAIN;
    int size = 12;
    Font f = new Font(fontname, style, size);
    jtextfield.setFont(f);
    NOTE: I haven't tested the above code. But it's the right idea.

  • How to set font for  JOptionPane.showMessageDialog() ?

    Hi,
    I want to set font for JOptionPane.showMessageDialog(). I have tried with following but it did not worked.
    javax.swing.UIManager.put("JOptionPane.font", "Verdana"); Do any one have idea how to do this. Your suggestion would be helpfull to me.
    Thank you.

    Then you'll have to loop over the components in the JOptionPane and setFont for each JButton. My SwingUtils class (search the net using Darryl SwingUtils, I can't give you a link as it's blocked from my office) can make this easier.
    Sample code:import darrylbu.util.SwingUtils;
    import java.awt.Font;
    import javax.swing.*;
    import javax.swing.plaf.FontUIResource;
    public class OptionPaneFonts {
       public static void main(String[] args) {
          UIManager.put("OptionPane.messageFont", new FontUIResource(new Font(
                  "Verdana", Font.BOLD, 32)));
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new OptionPaneFonts().makeUI();
       public void makeUI() {
          JOptionPane pane = new JOptionPane("So it's a date?",
                  JOptionPane.QUESTION_MESSAGE,
                  JOptionPane.YES_NO_CANCEL_OPTION,
                  UIManager.getIcon("OptionPane.questionIcon"),
                  new String[]{"Okey-dokey", "Not on your life!",
                     "Let me think about it"
                  }, null);
          for (JButton button : SwingUtils.getDescendantsOfType(JButton.class, pane)) {
             button.setFont(new Font("Tahoma", Font.ITALIC, 18));
          JDialog dialog = new JDialog((JWindow) null);
          dialog.setModal(true);
          dialog.add(pane);
          dialog.pack();
          dialog.setLocationRelativeTo(null);
          dialog.setVisible(true);
    }db
    Edited by: DarrylBurke -- shortened the code

  • How to set font for title and message in JOptionPane?

    Hi,
    I have following test code.
    JOptionPane.showMessageDialog(null, "Some Alert Message", "Alert", JOptionPane.ERROR_MESSAGE);In this code can we set font for "Some Alert Message", "Alert"?
    Regards,
    Kalyani......

    roll-your-own?
    import javax.swing.*;
    class Testing
      public static void main(String[] args)
        JDialog.setDefaultLookAndFeelDecorated(true);
        JOptionPane optionPane = new JOptionPane("<html><font size='5'>Your message here</font></html>");
        optionPane.setOptionType(JOptionPane.DEFAULT_OPTION);
        optionPane.setMessageType(JOptionPane.ERROR_MESSAGE);
        JDialog dialog = optionPane.createDialog(null, "Alert");
        dialog.getLayeredPane().getComponent(1).setFont(dialog.getFont().deriveFont(18f));//size = 18/whatever
        dialog.setModal(true);
        dialog.setVisible(true);
    }

  • How to set Font to the ToolTip in JComboBox

    Hi,
    I am having problem in setting font to the ToolTip for JComboBox.
    Help needed asap...
    TIA,
    CK

    From the Mail menu bar click Mail > Preferences then select the Fonts & Colors tab.
    You can reset fonts sizes from there.
    Another way to open Mail Preferences, with Mail running, press Command ,  (comma) on your keyboard.
    The Mavericks upgrade may have reset that data to factory settings.

  • WLC AireOS 8.0 - how to set font-color for integrated webauth/weblogin?

    Hello,
    up to AireOS 7.6 I was able to set the font-color of the internal webauth/weblogin page using html-codes, for example like this:
    Headline: Welcome to our <font color="red">guest</font>-network!
    Message: You need a valid <font color="blue">user</font> to login.
    Now with AireOS 8.0 this doesn't work anymore. When I try to set a headline or message with font-tags I get "Error while setting headline." (or "...message.") when I hit apply. I have to remove the font-tag to save the weblogin page.
    #CLIWEB-6-CLIWEB_INVALID_HTML_TAGS_USED: [PA] cli_web_api.c:1748 The Customization message field has invalid html tags
    #CLIWEB-6-CLIWEB_INVALID_HTML_TAGS_USED: [PA] cli_web_api.c:1663 The Headline field has invalid html tags
    So, how can we now set different font colors/styles like in previous releases? Using external or uploading selfmade pages is not an option.
    Thanks,
    Chris

    Since your using code to change the default internal portal page look, its better for you just to create a custom webauth and upload that to the WLC.  That is how I do my implementations as its easier for me to create a new page than trying to mess around with the internal page.  As you can see, Cisco can change the way things work in every version.  It might just be the fact that they no longer are allowing html code to be inserted in the default webauth/passthrough page.
    Scott

  • How to set Fonts size in X (whole system)

    Hi,
    I just bought a 19" monitor, and finally, got my resolution up from 800x600 to find out that i cant get to increse the xterm, Eterm, Firefox, Thunderbird, Gaim and everything to have an acceptable font size...
    I mean, is there a way to set the whole system font to some minimal size?
    I know how to change in almost every app (have to see if they can remember it, but thats just checking) but there are some i dont... xterm for example...ive looked at the man page, but there are so many options (just with the font subject, i do use several of the other flags) that i couldnt find the one i wanted, just to increase the font size... in Eterm there are 4 pre-set sizes, although i would like to increse it a bit more...
    I use Enlightenment, so i dont have any Gnome/KDE control center to do anything...
    As usual, any tips are welcome!
    Thanks!

    I can't provide much help but I can give you a hint: change the DPI globally with... one sec... xfce has some sort of script for settings the DPI globally...
    This is the part where the DPI is set
    # Those are my settings, change them as appropriate...
    # Xft DPI: 96
    # Xft.hintstyle: hintnone/hintslight/hintmedium/hintfull
    # Xft hinting: 1/0
    xrdb -nocpp -merge - << EOF
    Xft.dpi: 96
    Xft.hinting: 1
    Xft.hintstyle: hintmedium
    EOF
    You might run the command with another DPI setting...
    xrdb can be found in /usr/X11R6/bin.
    Once again, this is just a thought, I don't know how successful this change will be. Good luck.
    You might want to have a look on Google.
    IceRAM

  • How to set font Color in Mail

    Sometime ago I set in Mail the default font to Arial, and the default font Size to 18, so when I write a new email these are my default font and size. But I could not set the font Color. How do I do this?

    Sounds like you have the Preferences toolbar closed on another selection.
    Go to Mail > Preferences and at the top right of the Preferences window is a clear pill shaped button.
    Selecting this button opens/closes the complete Preferences toolbar.

  • How to set font in StyleConstants class??

    Font Style should be int, in new Font(string fonta,int Style,int Size)
    fonta is like "RomanC", Style is like 1 --"underline",Size is like 12
    StyleConstants.setFontSize(lAttr, int Size);
    StyleConstants.setFontFamily(lAttr, String fonta);
    fonta is a String ,but Style is a int,I should do????

    hello,
    JTextPane textPane = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();
    // Makes text red
    Style style = textPane.addStyle("Red", null);
    StyleConstants.setForeground(style, Color.red);
    // Inherits from "Red"; makes text red and underlined
    style = textPane.addStyle("Red Underline", style);
    StyleConstants.setUnderline(style, true);
    // Makes text 24pts
    style = textPane.addStyle("24pts", null);
    StyleConstants.setFontSize(style, 24);
    // Makes text 12pts
    style = textPane.addStyle("12pts", null);
    StyleConstants.setFontSize(style, 12);
    // Makes text italicized
    style = textPane.addStyle("Italic", null);
    StyleConstants.setItalic(style, true);
    // A style can have multiple attributes; this one makes text bold and italic
    style = textPane.addStyle("Bold Italic", null);
    StyleConstants.setBold(style, true);
    StyleConstants.setItalic(style, true);
    // Set text in the range [5, 7) red
    doc.setCharacterAttributes(5, 2, textPane.getStyle("Red"), true);
    // Italicize the entire paragraph containing the position 12
    doc.setParagraphAttributes(12, 1, textPane.getStyle("Italic"), true);
    -kannan

  • How to set font size...

    Hi, I'm trying to make the font size of a link 16px, how can I do this? I am trying:
    Currently, I have:
    <b><hbj:link
    id="link1"
    text="Link to google"
    reference="http://www.google.com"
    target="_TOP"
    tooltip="this takes you to: http://www.google.com"
    onClick="LinkClick">
    <% link1.setFontSize(LinkFontSize.STANDARD);%>
    </hbj:link></b>
    But I would like the size of the font link to be 16px.
    I see that there is a constructor available in the JavaDocs but it is protected, how would I be able to use it?
    I'm a beginner in JSP and Java, so any examples, code, or suggestions are greatly appreciated!
    Thanks so much!
    Baggett.

    You can't use the LinkFontSize to change the font size but you have an alternative. you could do the following. You can pass your text for your link in html text and set the encoding to false.
    <b><hbj:link
    id="link1"
    text="<h1>Link to google</h1>"
    reference="http://www.google.com"
    target="_TOP"
    tooltip="this takes you to: http://www.google.com"
    onClick="LinkClick">
    <% link1.getInnerText().setEncode(false);%>
    </hbj:link></b>
    PS: Please Post your question in one forum.

  • Set font color to JTextPane

    I wrote a small program only 70 lines. These codes traverse all the text line by line, show all digits in blue color, but I do not know why, you see, there is something wrong, some characters are not updated correctly. but why?
    import javax.swing.*;
    import java.awt.Color;
    import javax.swing.text.*;
    public class MainWnd extends JFrame{
    private JTextPane textPane = new JTextPane();
    public MainWnd() {
    getContentPane().add(textPane);
    textPane.setText("1234567890\r\n1234567890\r\n1234567890\r\n1234567890\r\n1234567890\r\n");
    setBounds(100, 100, 400, 400);
    formatHighlight(textPane);
    show();
    public void formatHighlight(JTextPane textPane) {
    String text = textPane.getText();
    int begin = 0;
    int end = text.length() - 1;
    System.out.println("First, set all text black color: begin:" + begin + " end:" + end);
    System.out.println("All text is #" + text.substring(begin, end + 1)+"#");
    //reset all as default color black
    setTextColor(textPane, begin, end + 1, Color.BLACK);
    for (int i = begin; i <= end; ) {
    char c = text.charAt(i);
    //digital
    if (Character.isDigit(c)) {
    i = transactDigit(textPane, text, i);
    continue;
    //others
    System.out.println("skip others at i:" + i + " c:" + c);
    i++;
    private void setTextColor(final JTextPane sourcePane,
    final int offset, final int endPos, final Color color) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    MutableAttributeSet attr = new SimpleAttributeSet();
    StyleConstants.setForeground(attr, color);
    if (offset != endPos) {
    StyledDocument doc = (StyledDocument) sourcePane.getDocument();
    doc.setCharacterAttributes(offset, endPos - offset, attr, false);
    private int transactDigit(JTextPane sourcePane, String text, int offset) {
    int endPos = 0;
    for (endPos = offset; endPos < text.length(); endPos++) {
    char c = text.charAt(endPos);
    if (!Character.isDigit(c))
    break;
    System.out.println("set digit blue color from " + offset + " to " + (endPos-1));
    System.out.println("The digit string is #" + text.substring(offset, endPos) + "#");
    setTextColor(sourcePane, offset, endPos, Color.BLUE);
    return endPos;
    public static void main(String[] args) {
    MainWnd mainWnd = new MainWnd();
    Pls, help!

    I have found the reason. replace
    String text = textPane.getText();
    with
    String text = textPane.getDocument().getText(0, textPane.getDocument().getLength());
    It's because the document (model) does not contain '\r', but the view does.
    Thx for your enthusiasm.

  • How to set selected text on JTextPane ?

    I need to set selected text on a JTextPane. I used setSelectionStart(); and setSelectionEnd(); but it doesn't work.
    Can anybody help me?

    I'm not sure if this is what you are looking for, but the following code sample was revised from the tutorial TextSamplerDemo.java. It will hightlight the word "selected" in yellow in the JTextPane.
    //created with j2sdk1.4.0_01
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;      
    public class SelectedText extends JFrame {
        public SelectedText() {
            super("Selected Text");       
            //Create a text pane.
            JTextPane 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));
            Container pane = getContentPane();
            pane.add(paneScrollPane);
        private JTextPane createTextPane() {
            JTextPane textPane = new JTextPane();
            String[] initString =
                    { "This is the ", //regular
                      "selected",     //selected
                      " text. "       //regular
            String[] initStyles = {"regular", "selected", "regular"};
            initStylesForTextPane(textPane);
            Document doc = textPane.getDocument();
            try {
                for (int i=0; i < initString.length; i++) {
                    doc.insertString(doc.getLength(), initString,
    textPane.getStyle(initStyles[i]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text.");
    return textPane;
    protected void initStylesForTextPane(JTextPane textPane) {
    //Initialize some styles.
    Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = textPane.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "SansSerif");
    Style s = textPane.addStyle("selected", regular);
    StyleConstants.setBackground(s, Color.YELLOW);
    public static void main(String[] args) {
    JFrame frame = new SelectedText();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.pack();
    frame.setVisible(true);
    S.L.

Maybe you are looking for

  • Facing error while exporting a table from command prompt.

    Hi Everyone, Please see the below error and suggest me what to do? My database is 11g. SQL> connect system/manager; Connected. SQL> expdp scott directory=test_dir dumpfile=scott.dmp tables=emp; SP2-0734: unknown command beginning "expdp scot..." - re

  • Why no "Create AAC version" option?

    Using several online tutorials as a guide, I'm trying to use iTunes 10 (Windows XP) to convert a 30-second mp3 file into a ringtone. The tutorials say that even in 10, I should be able to right-click a song and have "Create AAC version" on the contex

  • Getting exception error FUNCMOD_NOT_FOUND

    getting exception error FUNCMOD_NOT_FOUND Regards Rabin

  • My call register is not working

    Y is my call register not working at all

  • Dragging guides

    Hi, I'm trying to learn InDesign and I have the Adobe Indesign CC classroom in a book.  It says that when you want to drag a guide from a ruler you should drag a ruler guide down and the value is displayed next to the pointer while you are dragging i