Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Problem with JTextPane indentation

  1. #1
    Junior Member Dachre's Avatar
    Join Date
    Oct 2014
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Problem with JTextPane indentation

    About a thousand years ago, I wrote a simple text console, extending JTextArea, for viewing throughput in plain text format. Recently, I decided I wanted to make a fancier, schmancier, stylable version of the same thing, extending JTextPane instead.

    Basically, I wanted five additional features: set the font family, set the color, set bold, set italic, and hanging first-line indentation, i.e., the first line is butted against the margin, and successive (wrapped) lines are indented fifty units or so. The first four were cake, the last one is giving me heck. Heck in that I can't indent anything at all, much less get the hanging indent I wanted.

    Things I have already tried:
    • StyleConstants.setLeftIndent(style, indent)
      • I've tried putting this absolutely everywhere: the constructor, the methods, everywhere. I even tried throwing in a public mutator and setting it from the code where I actually instantiate the console itself. Nada. Nothin.
    • Removing all Styles from the StyledDocument except one
      • I was using multiple styles, one for the timestamp, and one for the customized text. Thinking that this might be the problem, I removed every ounce of customized text, commented out all instances of the custom style, and reverted the entire document to a single style, a default one. Still nothing. No indentation whatsoever: no first line, no paragraph, nothing.
    • Adding the console object to the main GUI frame in about a thousand different ways
      • Thinking that the problem might lie in a LayoutManager, or some other GUI component, I tried adding the console object to the main frame in every imaginable way. I tried adding it by itself (frame.add(console, BorderLayout.CENTER)). I tried adding it to a panel, and then the panel to the layout. I tried adding it to almost all of the different layout managers, Flow, Box, Grid, Group, etc. Absolutely nothing. No indentation at all.
    • Probably some other things I'm forgetting—I've been working on this for two days.


    I'm going to paste the entire .java file for the custom class below. Hopefully someone can figure out exactly what it is I'm doing wrong. The indentation isn't absolutely necessary for what I'm trying to accomplish with this class, but this problem is bugging the heck out of me, because I've seen plenty of code to know that it should work, it's just not. Most of the things I tried, chiefly the instances of attempting to set the left indent, have already been removed. But trust me, they were everywhere.

    If anyone can help me with what I'm doing wrong here, it'd be greatly appreciated.

    /*≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
       PROJECT:                   GenUtils
       AUTHOR:                    DCR
       DATE:                      2012-10-24
       FILENAME:                  DCRAdvancedTextConsole.java
       PURPOSE:                   A styled text console for output, whatever.
       VERSION:                   20141009-1121
    ≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡*/
    package IRP;  //Added 2014.10.08 for IRP project
     
    //=[BEGIN IMPORTS]==============================================================
    import java.awt.Color;
    import java.awt.GraphicsEnvironment;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Date;
    import javax.swing.JTextPane;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledDocument;
    //=[END IMPORTS]================================================================
     
    //=[BEGIN CLASS DCRAdvancedTextConsole]=========================================
    public class DCRAdvancedTextConsole extends JTextPane
    {
        //-[BEGIN DATA MEMBERS]-----------------------------------------------------
        public static final int INS_BEG = 0;
        public static final int INS_END = 1;
     
        private final boolean               insertAtTop;
        private final Style                 dStyle;
        private final Style                 cStyle;
        private final StyledDocument        doc;    
        //-[END DATA MEMBERS]-------------------------------------------------------
     
        //-[BEGIN CONSTRUCTOR(S)]---------------------------------------------------
        DCRAdvancedTextConsole(int insertMode)
        {
            insertAtTop = insertMode == INS_BEG;
     
            doc = getStyledDocument();
            dStyle = addStyle("Default", null);
            cStyle = addStyle("Custom", null);
     
            StyleConstants.setLeftIndent(dStyle, 15);
     
            setEditable(false);
        }
        //-[END CONSTRUCTOR(S)]-----------------------------------------------------
     
        //-[BEGIN METHOD addLine]---------------------------------------------------
        public final void addLine(String s, Color c, boolean bold, boolean italic)
        {
            StyleConstants.setForeground(cStyle, c);
            StyleConstants.setBold(cStyle, bold);
            StyleConstants.setItalic(cStyle, italic);
     
            String ts = new SimpleDateFormat("[hh:mm:ss a] ").format(new Date());
     
            try
            {
                if(insertAtTop)
                {
                    doc.insertString(0, ts, dStyle);
                    doc.insertString(0, s + "\n", cStyle);
                    setCaretPosition(0);
                }
                else
                {
                    doc.insertString(doc.getLength(), ts, dStyle);
                    doc.insertString(doc.getLength(), s + "\n", cStyle);
                    setCaretPosition(doc.getLength());
                }
            }
            catch(BadLocationException e)
            {
                System.out.println("Caught BadLocationException within "
                    + "DCRAdvancedTextConsole.addLine().  This should never happen, "
                    + "but stranger things have occurred.");
            }
        }
        //-[END METHOD addLine]-----------------------------------------------------
     
        //-[BEGIN METHOD printTestStrings]------------------------------------------
        public void printTestStrings()
        {
            addLine("Blue text, no bold, no italic.", Color.BLUE, false, false);
            addLine("Red text, bold, no italic.", Color.RED, true, false);
            addLine("Green text, no bold, italic.", Color.GREEN, false, true);
        }
        //-[END METHOD printTestStrings]--------------------------------------------
     
        //-[BEGIN METHOD setFontFamily]---------------------------------------------
        public void setFontFamily(String family)
        {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            ArrayList al = new ArrayList(Arrays.asList(ge.getAvailableFontFamilyNames()));
     
            if(al.contains(family))
            {
                StyleConstants.setFontFamily(dStyle, family);
                StyleConstants.setFontFamily(cStyle, family);
            }
            else
            {
                StyleConstants.setFontFamily(dStyle, "Dialog");
                StyleConstants.setFontFamily(cStyle, "Dialog");
            }
        }
        //-[END METHOD setFontFamily]-----------------------------------------------
     
        //-[BEGIN METHOD setFontSize]-----------------------------------------------
        public void setFontSize(int size)
        {
            StyleConstants.setFontSize(dStyle, size);
            StyleConstants.setFontSize(cStyle, size);
        }
        //-[END METHOD setFontSize]-------------------------------------------------
    }
    //=[END CLASS DCRAdvancedTextConsole]===========================================
     
    //≡[EOF]≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡


  2. #2
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Problem with JTextPane indentation

    This works for me, perhaps it will help you:
    import java.awt.EventQueue;
     
    import javax.swing.JFrame;
    import javax.swing.JTextPane;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DefaultStyledDocument;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
     
    import java.awt.BorderLayout;
     
    public class JTextPaneTest {
     
    	public static void main(String[] args) {
    		EventQueue.invokeLater(new Runnable() {
    			public void run() {
    				try {
    					JTextPaneTest window = new JTextPaneTest();
    					window.frame.setVisible(true);
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		});
    	}
     
    	private JFrame frame;
     
    	public JTextPaneTest() {
    		frame = new JFrame();
    		frame.setSize(640, 480);
    		frame.setLocationRelativeTo(null);
     
    		StyleContext styleContext = new StyleContext();
    		Style defaultStyle = styleContext.getStyle(StyleContext.DEFAULT_STYLE);
    		Style mainStyle = styleContext.addStyle("IndentedStyle", defaultStyle);
    		StyleConstants.setLeftIndent(mainStyle, 32);
     
    		DefaultStyledDocument doc = new DefaultStyledDocument(styleContext);
    		doc.setLogicalStyle(0, mainStyle);
    		try {
    			doc.insertString(0, "Hello World", (AttributeSet) null);
    		} catch (BadLocationException e) {
    			e.printStackTrace();
    		}
     
    		JTextPane txtpnBla = new JTextPane(doc);
    		frame.getContentPane().add(txtpnBla, BorderLayout.CENTER);
    	}
     
    }

  3. The Following User Says Thank You to Cornix For This Useful Post:

    GregBrannon (October 9th, 2014)

  4. #3
    Junior Member Dachre's Avatar
    Join Date
    Oct 2014
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Problem with JTextPane indentation

    Cornix:

    Thanks for the reply. I reconfigured my pane's code a little to reflect the methods you used to set up yours in your example. Indentation now works perfectly, but unfortunately, my foreground, bold, and italic settings now don't.

    I'm not sure if the problem is that I'm trying to insert text with two different styles onto the same line or what, but I think I'm still just not doing something right. I'll throw an updated version of the code in (with functional indentation). Maybe you or someone else can see where I'm messing it up at.

    /*≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
       PROJECT:                   GenUtils
       AUTHOR:                    DCR
       DATE:                      2012-10-24
       FILENAME:                  DCRAdvancedTextConsole.java
       PURPOSE:                   A styled text console for output, whatever.
       VERSION:                   20141009-1424
    ≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡*/
    package IRP;  //Added 2014.10.08 for IRP project
     
    //=[BEGIN IMPORTS]==============================================================
    import java.awt.Color;
    import java.awt.GraphicsEnvironment;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Date;
    import javax.swing.JTextPane;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DefaultStyledDocument;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
    import javax.swing.text.StyledDocument;
    //=[END IMPORTS]================================================================
     
    //=[BEGIN CLASS DCRAdvancedTextConsole]=========================================
    public class DCRAdvancedTextConsole extends JTextPane
    {
        //-[BEGIN DATA MEMBERS]-----------------------------------------------------
        public static final int INS_BEG = 0;
        public static final int INS_END = 1;
     
        private final boolean               insertAtTop;
        private final Style                 dStyle;
     
        private Style                       cStyle;
        private StyleContext                styleContext;
    //    private final StyledDocument        doc;  
        private DefaultStyledDocument       doc;
        //-[END DATA MEMBERS]-------------------------------------------------------
     
        //-[BEGIN CONSTRUCTOR(S)]---------------------------------------------------
        DCRAdvancedTextConsole(int insertMode)
        {
            insertAtTop = insertMode == INS_BEG;
     
    //        doc = getStyledDocument();
    //        dStyle = addStyle("Default", null);
    //        cStyle = addStyle("Custom", null);
     
            styleContext = new StyleContext();
            dStyle = styleContext.getStyle(StyleContext.DEFAULT_STYLE);
            cStyle = styleContext.addStyle("CUSTOM", dStyle);
            StyleConstants.setLeftIndent(cStyle, 50f);
            StyleConstants.setFirstLineIndent(cStyle, -50f);
            doc = new DefaultStyledDocument(styleContext);
            this.setDocument(doc);
     
            setEditable(false);
        }
        //-[END CONSTRUCTOR(S)]-----------------------------------------------------
     
        //-[BEGIN METHOD addLine]---------------------------------------------------
        public final void addLine(String s, Color c, boolean bold, boolean italic)
        {
            StyleConstants.setForeground(cStyle, c);
            StyleConstants.setBold(cStyle, bold);
            StyleConstants.setItalic(cStyle, italic);
     
            String ts = new SimpleDateFormat("[hh:mm:ss a] ").format(new Date());
     
            try
            {
                if(insertAtTop)
                {
                    doc.setLogicalStyle(0, dStyle);
                    doc.insertString(0, ts, (AttributeSet)null);
                    doc.setLogicalStyle(0, cStyle);
                    doc.insertString(0, s + "\n", (AttributeSet)null);
                    setCaretPosition(0);
                }
                else
                {
                    doc.setLogicalStyle(doc.getLength(), dStyle);
                    doc.insertString(doc.getLength(), ts, (AttributeSet)null);
                    doc.setLogicalStyle(doc.getLength(), cStyle);
                    doc.insertString(doc.getLength(), s + "\n", (AttributeSet)null);
                    setCaretPosition(doc.getLength());
                }
            }
            catch(BadLocationException e)
            {
                System.out.println("Caught BadLocationException within "
                    + "DCRAdvancedTextConsole.addLine().  This should never happen, "
                    + "but stranger things have occurred.");
            }
        }
        //-[END METHOD addLine]-----------------------------------------------------
     
        //-[BEGIN METHOD printTestStrings]------------------------------------------
        public void printTestStrings()
        {
            addLine("Blue text, no bold, no italic.", Color.BLUE, false, false);
            addLine("Red text, bold, no italic.", Color.RED, true, false);
            addLine("Green text, no bold, italic.", Color.GREEN, false, true);
        }
        //-[END METHOD printTestStrings]--------------------------------------------
     
        //-[BEGIN METHOD setFontFamily]---------------------------------------------
        public void setFontFamily(String family)
        {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            ArrayList al = new ArrayList(Arrays.asList(ge.getAvailableFontFamilyNames()));
     
            if(al.contains(family))
            {
                StyleConstants.setFontFamily(dStyle, family);
                StyleConstants.setFontFamily(cStyle, family);
            }
            else
            {
                StyleConstants.setFontFamily(dStyle, "Dialog");
                StyleConstants.setFontFamily(cStyle, "Dialog");
            }
        }
        //-[END METHOD setFontFamily]-----------------------------------------------
     
        //-[BEGIN METHOD setFontSize]-----------------------------------------------
        public void setFontSize(int size)
        {
            StyleConstants.setFontSize(dStyle, size);
            StyleConstants.setFontSize(cStyle, size);
        }
        //-[END METHOD setFontSize]-------------------------------------------------
    }
    //=[END CLASS DCRAdvancedTextConsole]===========================================
     
    //≡[EOF]≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡


    --- Update ---

    OK, after a decent amount of experimentation and looking-up-things-in-the-API-docs, I used a combination of what Cornix suggested, and a SimpleAttributeSet to accomplish exactly what I was going for. Here is the updated java class that functions as originally desired:

    /*≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
       PROJECT:                   GenUtils
       AUTHOR:                    DCR
       DATE:                      2012-10-24
       FILENAME:                  DCRAdvancedTextConsole.java
       PURPOSE:                   A styled text console for output, whatever.
       VERSION:                   20141009-1524
    ≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡*/
    package IRP;  //Added 2014.10.08 for IRP project
     
    //=[BEGIN IMPORTS]==============================================================
    import java.awt.Color;
    import java.awt.GraphicsEnvironment;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Date;
    import javax.swing.JTextPane;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DefaultStyledDocument;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
     
    //=[BEGIN CLASS DCRAdvancedTextConsole]=========================================
    public class DCRAdvancedTextConsole extends JTextPane
    {
        //-[BEGIN DATA MEMBERS]-----------------------------------------------------
        public static final int INS_BEG = 0;
        public static final int INS_END = 1;
     
        private final boolean               insertAtTop;
        private final Style                 dStyle;
        private final Style                 cStyle;
        private final StyleContext          styleContext;
        private final DefaultStyledDocument doc;
        //-[END DATA MEMBERS]-------------------------------------------------------
     
        //-[BEGIN CONSTRUCTOR(S)]---------------------------------------------------
        DCRAdvancedTextConsole(int insertMode)
        {
            insertAtTop = insertMode == INS_BEG;
     
            styleContext = new StyleContext();
            dStyle = styleContext.getStyle(StyleContext.DEFAULT_STYLE);
            cStyle = styleContext.addStyle("CUSTOM", dStyle);
            StyleConstants.setLeftIndent(cStyle, 50f);
            StyleConstants.setFirstLineIndent(cStyle, -50f);
            doc = new DefaultStyledDocument(styleContext);
            setDocument(doc);
     
            setEditable(false);
        }
        //-[END CONSTRUCTOR(S)]-----------------------------------------------------
     
        //-[BEGIN METHOD addLine]---------------------------------------------------
        public final void addLine(String s, Color c, boolean bold, boolean italic)
        {
            SimpleAttributeSet attribs = new SimpleAttributeSet();
            StyleConstants.setForeground(attribs, c);
            StyleConstants.setBold(attribs, bold);
            StyleConstants.setItalic(attribs, italic);
     
            String ts = new SimpleDateFormat("[hh:mm:ss a] ").format(new Date());
     
            try
            {
                if(insertAtTop)
                {
                    doc.setLogicalStyle(0, cStyle);
                    doc.insertString(0, s + "\n", attribs);
                    doc.setLogicalStyle(0, dStyle);
                    doc.insertString(0, ts, (AttributeSet)null);
                    setCaretPosition(0);
                }
                else
                {
                    doc.setLogicalStyle(doc.getLength(), dStyle);
                    doc.insertString(doc.getLength(), ts, (AttributeSet)null);
                    doc.setLogicalStyle(doc.getLength(), cStyle);
                    doc.insertString(doc.getLength(), s + "\n", attribs);
                    setCaretPosition(doc.getLength());
                }
            }
            catch(BadLocationException e)
            {
                System.out.println("Caught BadLocationException within "
                    + "DCRAdvancedTextConsole.addLine().  This should never happen, "
                    + "but stranger things have occurred.");
            }
        }
        //-[END METHOD addLine]-----------------------------------------------------
     
        //-[BEGIN METHOD printTestStrings]------------------------------------------
        public void printTestStrings()
        {
            addLine("Blue text, no bold, no italic.", Color.BLUE, false, false);
            addLine("Red text, bold, no italic.", Color.RED, true, false);
            addLine("Green text, no bold, italic.", Color.GREEN, false, true);
        }
        //-[END METHOD printTestStrings]--------------------------------------------
     
        //-[BEGIN METHOD setFontFamily]---------------------------------------------
        public void setFontFamily(String family)
        {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            ArrayList al = new ArrayList(Arrays.asList(ge.getAvailableFontFamilyNames()));
     
            if(al.contains(family))
            {
                StyleConstants.setFontFamily(dStyle, family);
                StyleConstants.setFontFamily(cStyle, family);
            }
            else
            {
                StyleConstants.setFontFamily(dStyle, "Dialog");
                StyleConstants.setFontFamily(cStyle, "Dialog");
            }
        }
        //-[END METHOD setFontFamily]-----------------------------------------------
     
        //-[BEGIN METHOD setFontSize]-----------------------------------------------
        public void setFontSize(int size)
        {
            StyleConstants.setFontSize(dStyle, size);
            StyleConstants.setFontSize(cStyle, size);
        }
        //-[END METHOD setFontSize]-------------------------------------------------
    }
    //=[END CLASS DCRAdvancedTextConsole]===========================================
     
    //≡[EOF]≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡

    Thanks for the help with getting this working.

Similar Threads

  1. [SOLVED] saving a jTextPane input
    By mrgregglles in forum What's Wrong With My Code?
    Replies: 3
    Last Post: November 10th, 2013, 06:26 AM
  2. How to enable wrapping in JTextPane
    By kcaz in forum AWT / Java Swing
    Replies: 7
    Last Post: December 2nd, 2012, 03:04 PM
  3. JTextPane questions.
    By sunde in forum AWT / Java Swing
    Replies: 1
    Last Post: March 28th, 2011, 03:18 PM
  4. [SOLVED] JTextPane focus problem
    By LeonLanford in forum AWT / Java Swing
    Replies: 3
    Last Post: June 21st, 2010, 11:50 PM
  5. Java JTextPane Save
    By ikurtz in forum File I/O & Other I/O Streams
    Replies: 9
    Last Post: April 28th, 2010, 01:02 AM