Changing ui of JTextPane/StyledDocument

Hi,
i want to change the selection color of my text field, but i dont know why...is there a listing what i can change somewhere?
maze

At the start of your program, use the UIManager to change the default color:
UIManager.put("TextPane.selectionForeground", Color.red );
UIManager.put("TextPane.selectionBackground", Color.blue );For a list of all the UIManager properties you can change, see my program at:
http://www.discoverteenergy.com/files/ShowUIDefaults.java

Similar Messages

  • 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.

  • JTextPane, StyledDocuments

    Hello,
    I have just been studying the Documents and StyledDocuments, however I cannot get my JTextPane to show any of my data. I have a few questions:
    1. Does anyone know of a good practical tutorial for working with the JTextPane and a Styled Documents?
    2. Does anyone know of a set of classes that will interpret input from files other than plain text (take the binary input of a wordprocessing style file and display it correctly as formatted text in a JTextPane or some other Object)?
    3. Is there an easier way of dealing with formatting text than using a StyledDocument?
    4. Here is a copy of my code for the simple test I wrote with Styled Documents and JTextPanes: If possible can anyone tell me what is wrong with this?
    package FileReader;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    public class JTextPaneTest extends JFrame {
    private JTextPane txtPne = null;
    private DefaultStyledDocument docu = null;
    private StyleContext styles = new StyleContext();
    private JScrollPane pne = null;
    private StringContent strCon = new StringContent();
      public JTextPaneTest() {
        super("Stylized Text Pane");
        //SimpleAttributeSet set1 = new SimpleAttributeSet();
        Enumeration enum = styles.getStyleNames();
        while(enum.hasMoreElements()){
          System.out.println((String)enum.nextElement());
        try{
          strCon.insertString(0,"\tHere is some text\nThis is a simple Test\n\nNew Paragraph?");
          System.out.println(strCon.getString(0,strCon.length()));
        catch(BadLocationException e){
          e.printStackTrace();
        Style styl = styles.getStyle("default");
        StyleConstants.setBold(styl,false);
        StyleConstants.setFontSize(styl,14);
        StyleConstants.setFontFamily(styl,"SanSerif");
        docu = new DefaultStyledDocument(strCon,styles);
        txtPne = new JTextPane(docu);
        pne = new JScrollPane(txtPne);
        this.getContentPane().add(pne);
        this.setSize(400,400);
        this.setVisible(true);
      public static void main(String[] args) {
        final JTextPaneTest jTextPaneTest = new JTextPaneTest();
        jTextPaneTest.addWindowListener(
          new WindowAdapter(){
            public void windowClosing(WindowEvent e){
              System.exit(0);
    }Running the file does not show any value in the document, although I passed it an object that implements the Content interface.
    Any help greatly appreciated,
    Dan Hughes

    Here is a sample coding for u :-)
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.text.*;
    public class ColorTextPane extends JFrame {
    JTextPane text=new JTextPane();
    StyledDocument doc;
    SimpleAttributeSet set=new SimpleAttributeSet();
    public ColorTextPane()
    this.getContentPane().add(text,BorderLayout.NORTH);
    this.getContentPane().add(new JLabel("This is a simple JTextPane Demo !"),BorderLayout.CENTER);
    text.setText("This is a simple JTextPane Demo !");
    doc=text.getStyledDocument();
    StyleConstants.setForeground(set,Color.blue);
    try{
    doc.remove(10,6);
    doc.insertString(10,"simple",set);
    doc.remove(5,2);
    StyleConstants.setForeground(set,Color.red);
    StyleConstants.setFontFamily(set,"Chevera");
    StyleConstants.setFontSize(set,22);
    doc.insertString(5,"is",set);
    }catch(BadLocationException b){}
    this.setSize(250,120);
    this.setVisible(true);
    public static void main(String a[])
    new ColorTextPane();

  • CHANGE  FONT WITH JTEXTPANE

    I am using JTextPane and want the user to be able to highlight text and change font styles. How do I do this? I tried setFont but it does not work. Thanks.. Sarah

    Hello,
    did you try something like this :
    javax.swing.text.MutableAttributeSet attr = new javax.swing.text.SimpleAttributeSet();
    attr.addAttribute(javax.swing.text.StyleConstants.FontFamily, fontName);
    yourJTextPane.getStyledDocument().setCharacterAttributes(yourJTextPane.getSelectionStart(), yourJTextPane.getSelectionEnd() - yourJTextPane.getSelectionStart(), attr, false);

  • How to change focus within JTextPane

    Hi
    I have a JTextPane within a JScrollBar. I have a requirement to change the focus to particular line in the JTextPane on the click of a button. i.e. The JTextPane has to scroll down to that location on clicking the button. Do we have any built in APIs for this functionality ? Or how can we accomplish this ?

    play with modelToview and viewToModel methods to go where you want to go.
    Then you can set the caret position and request focus.

  • JTextPane StyledDocument insertString multi Icon problem (BUG?)

    Hi,
    Now I am trying to insert some icons to the StyledDocument of JTextPane.
    I found a problem that if I want to insert the same Icon (actually the same style which contains this icon) into the StyledDocument for more than one time, only the first insert operation works.
    But if I insert a whitespace (or other non-zero length text) between the twe icon, it can works. I don't know it's my mis-using of this StyledDocument or it's a bug of JTextPane and StyledDocument?
    Thanks!
    My sample code below: To Run this code, you need to add a "icon" named "t1.jpg" in your project directory ^_^
    import java.awt.BorderLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JTextPane;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
    import javax.swing.text.StyledDocument;
    public class JTextPaneInsertIcons
         public static void main(String[] args) throws Exception
              JTextPane pane = new JTextPane();
              ImageIcon icon = new ImageIcon("t1.jpg");
              StyledDocument styledDocument = pane.getStyledDocument();
              Style iconStyle = styledDocument.addStyle("icon", null);
              StyleConstants.setIcon(iconStyle, icon);
              styledDocument.insertString(styledDocument.getLength(), " ", iconStyle);
              styledDocument.insertString(styledDocument.getLength(), " ", iconStyle);
              styledDocument.insertString(styledDocument.getLength(), "\n", StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE));
              styledDocument.insertString(styledDocument.getLength(), " ", iconStyle);
              styledDocument.insertString(styledDocument.getLength(), " ", StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE));
              styledDocument.insertString(styledDocument.getLength(), " ", iconStyle);
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.getContentPane().add(pane, BorderLayout.CENTER);
              frame.setSize(360, 180);
              frame.setVisible(true);
    }

    OK, OK, I got it.
    Thank you so much!
    It seems I need to solve this problem ugly like this:
    import java.awt.BorderLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JTextPane;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.Element;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
    import javax.swing.text.StyledDocument;
    public class JTextPaneInsertIcons
         static StyledDocument styledDocument;
         public static void main(String[] args) throws Exception
              JTextPane pane = new JTextPane();
              ImageIcon icon = new ImageIcon("1.jpg");
              styledDocument = pane.getStyledDocument();
              Style iconStyle = styledDocument.addStyle("icon", null);
              StyleConstants.setIcon(iconStyle, icon);
              insertOne(iconStyle);
              insertOne(iconStyle);
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.getContentPane().add(pane, BorderLayout.CENTER);
              frame.setSize(600, 400);
              frame.setVisible(true);
         private static void insertOne(Style style) throws Exception
              if (style.getAttribute(StyleConstants.IconAttribute) != null)
                   if (styledDocument.getLength() > 0)
                        Element e = styledDocument.getCharacterElement(styledDocument.getLength() - 1);
                        AttributeSet attributeSet = e.getAttributes();
                        if (style.getAttribute(StyleConstants.IconAttribute) == attributeSet
                                  .getAttribute(StyleConstants.IconAttribute))
                             styledDocument.insertString(styledDocument.getLength(), " ", StyleContext
                                       .getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE));
              styledDocument.insertString(styledDocument.getLength(), " ", style);
    }

  • Changing fonts in jtextpane

    Hi, I'm new to playing around with JTextPane's and I need to create a basic text editor. The problem I'm having is that when I select a new font and use the backspace, it generates many textUI exceptions (on my pc). When I run the same code on mac os x version 10.1.5, I don't get any of these exceptions. Maybe the problem is that my pc is using SDK 1.2.1, and my mac is running the java it was packaged with(which I believe is 1.3.1, but I'm not sure.) How do you find out what the java SDK version is on mac os x 10.1.5 anyway? I'm new to OS X as well. :-/
    please help me figure out what's wrong here, would updating my sdk on my pc fix this? Below is a very basic code sample that will illustrate my problem:
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*; //for JTextPane
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.text.rtf.*;
    public class basicMemo extends JFrame{
    Color bgColor=Color.white;
    String fontName="Monospaced";
    int fontSize=12;
    JTextPane textPane;
    JComboBox fontBox;
    JComboBox sizeBox;
    JPanel northPanel;
    File fName=null;
    DefaultStyledDocument doc;
    RTFEditorKit rtfKit;
    StyleContext context;
    Container c;
    JFileChooser chooser;
    public basicMemo(){
    c=getContentPane();
    context=new StyleContext();
    doc=new DefaultStyledDocument(context);
    textPane=new JTextPane();
    rtfKit=new RTFEditorKit();
    textPane.setEditorKit(rtfKit);
    textPane.setDocument(doc);
    northPanel=new JPanel();
    chooser=new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    initFonts();
    initTop();
    c.add(northPanel,BorderLayout.NORTH);
    c.add(textPane,BorderLayout.CENTER);
    setSize(300,300);
    show();
    public void initFonts(){
    String fontNames[]={"Monospaced", "TimesRoman", "Courier",
    "Arial"};
    fontBox=new JComboBox(fontNames);
    fontBox.setEditable(true);
    fontBox.setSelectedItem(fontName);
    fontBox.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e){
    fontName=fontBox.getSelectedItem().toString();
    MutableAttributeSet attr=new SimpleAttributeSet();
    StyleConstants.setFontFamily(attr,fontName);
    textPane.setCharacterAttributes(attr,false);
    String fontSizes[]={ "10","12","14","16","20","24","36","48","72"};
    sizeBox=new JComboBox(fontSizes);
    sizeBox.setEditable(true);
    sizeBox.setSelectedItem(fontSize+"");
    sizeBox.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e){
    int size=0;
    try{
    size=Integer.parseInt(sizeBox.
    getSelectedItem().toString());
    catch(NumberFormatException ex) {
    return;}
    fontSize=size;
    MutableAttributeSet attr=new SimpleAttributeSet();
    StyleConstants.setFontSize(attr,size);
    textPane.setCharacterAttributes(attr,false);
    //top panel
    public void initTop(){
    northPanel.setLayout(new FlowLayout());
    northPanel.add(fontBox);
    northPanel.add(sizeBox);
    public static void main(String args[]){
    new basicMemo();
    }

    I checked my java version on my mac, and its 1.3.1.
    So I thought that I would update my pc's java to 1.3.1.
    After doing that, and verifying that it was updated,
    I still get the s ame exceptions when I use backspace
    on a new font!!! I just don't get it.
    Maybe it doesn't have to do with the java version, maybe its a computer
    setting or something. I'd switch to the mac and program
    it on that, however that seems ridiculous that it
    would refuse to work on my pc. Any suggestions?
    im running win98 SE on the pc, if that helps anyone.

  • Changing font to a custom font - styleddocument

    hello
    i've been trying to change the font in a styleddocument to a custom one that is not registered on the pc
    (i'm trying to make an application that holds the fonts in a folder, so that they can be dynamically loaded when needed)
    until now nothing worked
    i've tried 2 ways atm:
            JTextPane background = new JTextPane();
            StyledDocument styledDoc = background.getStyledDocument();
            if (styledDoc instanceof AbstractDocument) {
                doc = (AbstractDocument)styledDoc;
            } else {
                System.err.println("Text pane's document isn't an AbstractDocument!");
            initAttributes();
            background.setBackground(Color.BLACK);
            background.setEditable(false);
            File file = new File("fonts/mCode15.ttf");
         FileInputStream fis = null;
            Font font = null;
            try {
                fis = new FileInputStream(file);
                font = Font.createFont(Font.TRUETYPE_FONT, fis);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(MatrixWindow.class.getName()).log(Level.SEVERE, null, ex);
            } catch (FontFormatException ex) {
                Logger.getLogger(MatrixWindow.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(MatrixWindow.class.getName()).log(Level.SEVERE, null, ex);
            background.setFont(font);    // FAILS
            SimpleAttributeSet attrs = new SimpleAttributeSet();
            StyleConstants.setFontSize(attrs, 12);
            StyleConstants.setBold(attrs, true);
            StyleConstants.setForeground(attrs, Color.WHITE);
            StyleConstants.setFontFamily(font.getFontFamily);      // FAILSdoes anybody know any working solution for CUSTOM fonts?

    You should override public Font getFont(AttributeSet attr) method to return proper font with attributes.
    See how it works in src of DefaultStyledDocument class.
    Regards,
    Stas

  • How do I listen for changes in a container's components?

    I have a JScrollPane that contains a JTextPane. I want any Container that can possibly contain my JScrollPane to be able to listen for changes in the JTextPane's Document.
    For example, at the moment I'm using a JTabbedPane to hold a number of my JScrollPanes and I want to alter the tab title when any associated JScrollPane-JTextPane-Document is updated.
    Any suggestions on how best to handle this?

    I would use a controller object that manages all your gui components (tabs, scrolls, documents, text panes). Your controller object can register as a listener to the appropriate component, and when it changes, update the title of a tab (or do whatever else) as appropriate.
    Never put business logic like this stuff inside the actual gui components. Create, layout, etc. all the gui components (and related components like Document) from another controller like object instead. It makes handling the various listener stuff like this much easier. Read up on MVC (model view controller) stuff for more info.
    As for the actual mechanics, you could get the document that is used in the JTextPane and register as a DocumentListener. As a document listener, you get notified of all changes that are made to that document.

  • How do I make nodes in my JTree render as JTextPanes ?

    As a newbie to Java, I developed an application which started out by by having a user select a value in a JList and associated information was formatted nicely into a JTextPane (really it is just making some bold/italic/regular font switches).
    I now think it may be more visually appealing to represent the whole thing as a JTree, and the user would just click the +/- to access the associated information.
    So I would like substitute the JTree for the JList, while keep my nicely formatted JTextPane and am a bit stuck. I'd like each item in the JList to be a node and the information is going to be a leaf.
    Searching through the forums and other tutorials it I think I need to create a TreeCellRenderer that uses my JTextPane.
    Aside from advice such as Prior Planning Prevents Poor Performance, can someone give me a gentle kick in the right direction ? Pseudo-code or links would be great !
    Thanks in advance.

    Hi codingMonkey,
    I've looked at both of those (previously) but I've not got enough experience to figure out the coding bits for my application.
    So lets say I wanted to hack the JTextPane example here http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html and put a simple JTree in its place with three nodes and use the provided JTextPane as a text for the leafs.
    I think the important bits (except are addStylesToDocument) are this:
    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,
    doc.getStyle(initStyles[i]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
    return textPane;
    I don't really understand the TreeCellRenderer API link you sent and how to link the above JTextPane to the TreeCellRenderer.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Cannot UN-bold text in a JTextPane

    This is a strange one. I copied the code from my ap into the runable sample below. I can select a portion of text and then click the "Bold" button and the selected text gets turned to bold. Now if I select the bold text and click the bold button again, nothing happens. HOWEVER, if I select ANY portion of the bold text except for the very last character then I can unbold it.
    If I ever select the very last character of a bolded section it will not unbold the section. So I am always left with one character that I can not unbold.
    Any ideas what I'm doing wrong. (The relevant code from my real ap is what is inside the boldButton ActionListener)
    BTW: I'm a relative newbie to Java.
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.border.*;
    import java.awt.*;              //for layout managers and more
    import java.awt.event.*;        //for action events
    public class Bolder extends JPanel
        private String newline = System.getProperty("line.separator");
        private JTextPane textPane;
        private JLabel label;
        private JPanel parent;
        private JComponent dragging = null;
        private int mOffsetX, mOffsetY;
        public Bolder() {
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
            JToolBar toolBar = buildToolbar();
            add(toolBar);
            parent = new JPanel();
            add(parent);
            parent.setBackground( Color.white);
            parent.setPreferredSize(new Dimension(640, 480));
            // Create a text pane.
            textPane = createTextPane();
            textPane.setBounds(0, 0, 100, 100);
            Border myBorder = BorderFactory.createLineBorder( Color.red );
            textPane.setBorder(myBorder);
            parent.add(textPane);
        private JTextPane createTextPane() {
            String[] initString =
                { "This is some sample text ",
                    "including some bold ",
                    "That can be used for testing purposes."+newline+"If you bold a piece of text"+
                    " then it cannot be unbolded entirely. All but the last character can be unbolded."+newline+
                    "A most peculiar phenomenon."
            String[] initStyles =
                    { "regular", "bold", "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,
    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);
    private JToolBar buildToolbar() {
    JToolBar toolBar = new JToolBar();
    toolBar.setRollover( true );
    toolBar.setFloatable( false );
    JButton boldButton = new JButton("Bold");
    boldButton.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    AttributeSet current = textPane.getCharacterAttributes();
    if (current==null) {
    // if no currently selected text, apply bold to anything typed in the future
    // at this location.
    current = textPane.getInputAttributes();
    MutableAttributeSet attr = new SimpleAttributeSet();
    boolean bold = false;
    if (current.getAttribute(StyleConstants.Bold)!=null) {
    bold = (current.getAttribute(StyleConstants.Bold).toString()=="true") ? true : false;
    if (bold) {
    StyleConstants.setBold(attr, false);
    } else {
    StyleConstants.setBold(attr,true);
    textPane.setCharacterAttributes(attr, false);
    toolBar.add( boldButton );
    return toolBar;
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("Bolder");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new Bolder();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();

    Here's a work around that ALMOST works: surrounding the line
    bold = (current.getAttribute(StyleConstants.Bold).toString()=="true") ? true : false;Where I decide if the text was previous bolded or not, I add a call to textRegion.setSelectionEnd(...); to set the end of the selection to one character less, then get the attributes and then set the end of the selection back to the original position.
    The only problem is, it doesn't work if you select only one character to bold or unbold.
    --gary                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Label color not changing color

    hi,
    i'm having some problems trying to set the color or a jlabel, but it's not working. here is the code:
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.text.*;
    import java.awt.event.*;
    public class PaperTest extends DefaultStyledDocument{
         int maxLen;       
         public static void main(String args[]) {
              JFrame paper = new JFrame();
              GridLayout gd = new GridLayout(3,1);
              paper.getContentPane().setLayout(gd);
                 paper.addWindowListener(new WindowAdapter() {
                  public void windowClosing(WindowEvent e) {
                       System.exit(0);          
             JLabel header = new JLabel("Header");
             JLabel footer = new JLabel("Footer");
             header.setBackground(Color.BLUE);          //  Set the color here
             footer.setBackground(Color.WHITE);       //  Set the color here
              JTextPane tp = new JTextPane();
              StyledDocument doc = (StyledDocument)tp.getDocument();
              tp.setDocument(new PaperTest(11));
              tp.setBackground(Color.RED);
         //     tp.setFont(new java.awt.Font("Serif", 0, 24));
              tp.setForeground(Color.WHITE);
              paper.getContentPane().add(header);
              paper.getContentPane().add(tp);
              paper.getContentPane().add(footer);
              paper.setSize(100,100);
             paper.setVisible(true);
         public void insertString(int offset,String str, AttributeSet a) throws javax.swing.text.BadLocationException {
             if( getLength() + str.length() >= maxLen )
                  return;     
             super.insertString(offset, str, a);   
         public PaperTest(int maxLen) {     
                 super();     
                 this.maxLen = maxLen;               //  Set the max length (chars) allowed in Note
    }Any ideas?
    Thanks.

    Hi,
    header.setOpaque(true); // <--- important
    footer..setOpaque(true);
    header.setBackground(Color.BLUE);          // Set the colorhere
    footer.setBackground(Color.WHITE);
    A label is normally transparent and displays it's container's color, unless you set it opaque.
    HTH

  • Append() a string in TextArea vs. insertString on a Document in JTextPane

    I was using append() in TextArea to display some messages. Then I changed it to JTextPane and use insertString with the Document because I need to have some messages in color. The messages came out all right. But they won't get displayed on the fly.
    Can I make it display just like the behavior from the append() function with the TextArea?

    Hi,
    Please ask Swing questions in the Swing forum.
    Kaj

  • How to associate Document and JTextPane  ?

    Hello,
    I'm a little lost and confused about JTextPane.
    I thought that to associate a document and a JTextPane, the method JTextPane.setDocument(doc) had to be used.
    But by looking at the sample : http://bioportal.weizmann.ac.il/course/prog2/tutorial/uiswing/components/example-1dot4/TextSamplerDemo.java, I haven't seen any such instruction. The code is the following :
            JTextPane textPane = new JTextPane();
            StyledDocument doc = textPane.getStyledDocument();
            addStylesToDocument(doc);
            try {
                for (int i=0; i < initString.length; i++) {
                    doc.insertString(doc.getLength(), initString,
    doc.getStyle(initStyles[i]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
    I understand that the document "doc" is associated with  "textPane" , but I do not understand, how Java knows that in this JTextPane, the document to be displayed must be  "doc" ?  However it works (miracle ???).   
    I'm wondering whether it is  not because the Document Listener retrieves the JTextPane information from the Document, and then triggers the  JtextPane update from the document.  But I'm not sure.
    Thanks to gurus to let me understand.   
    Gege                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Thanks a lot Camickr for your answer. But does this mean that when I type :
    StyleDdocument doc = textPane.getStyledDocumen();
    I do not really create a document, but I only get the reference of the empty document ? If it is right, then I understand why the following code does not work.
    Among my various tries, I sightly modified the TextSamplerDemo sample to add a second JTextPane (that I did not add to the JPanel).
    JTextPane textPane = new JTextPane();
    JTextPane textPane2 = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();
    doc = textPane2.getStyledDocument();
    addStylesToDocument(doc);In such a case, textPane becomes empty, but when I add te instruction : textPane.setDocument(doc); it starts working again.
    Thanks again for your help, I hope you have understood my English (which is not my natural language).
    gege

  • Using jtextpane

    hi,
    im trying to use the JTextPane in such a way that i take input in the the JTextField and on hitting enter i send it to JTextPane. here im using the SETTEXT(STRING S) method to send the text to the JTextPane. the problem is this that all the code works well but the message is not shown on the text pane..................please give urgent response.

    Try the following
    // Do them during initialization
    JTextPane txtOutput = new JTextPane();
    StyledDocument document = txtOutput.getStyledDocument();
    // Define style for output
    Style normalStyle = document.addStyle("Normal", null);
    StyleConstants.setItalic(normalStyle, false);
    StyleConstants.setFontFamily(normalStyle, "Courier");
    StyleConstants.setFontSize(normalStyle, 11);
    StyleConstants.setForeground(normalStyle, Color.black);
    // Now to insert string at end
    document.insertString(document.getLength(), "Hello World!!!", normalStyle );Hope it helps
    Amitabh

Maybe you are looking for

  • Getting following error while deploying my webservice on weblogic 10.3

    hi I am tring to deploy a webservice (spring + cxf ) in weblogic 10.3 applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns

  • Can't delete items in sidebar in finder

    i can't delete a folder thats in the sidebar. when i command click all it says is "open sidebar preferences". when i try to move the folder over to the same folder thats in the sidebar it says "the alias (foldername) can't be found because the origin

  • Why are some channels offered on Select TV service not offered on Premium?

    We get the Premium TV Service (we're in Maryland).  The lower-priced Select service offers a number of channels that are not offered on Premium (but are offered on the higher priced plans).  We're particulary interested in the BBC chanels, but there

  • Order data

    Hi all, Is there anyway when you create an order it should save that order in xl file in pc or appln server. If possible please tell me how to do it. with regards chandu.

  • ISeries DB2 JDBC Adapter failure

    I have a scenario where XI needs to send data to AS-400 (iSeries) DB2. To do that we installed the DB2 JDBC driver for AS-400 (jt400.jar). However, we are getting the following error: Receiver Adapter v2808 for Party '', Service 'Phase2Test_BusServic