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 8 of 8

Thread: How to enable wrapping in JTextPane

  1. #1
    Junior Member
    Join Date
    Dec 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default How to enable wrapping in JTextPane

    Hi, I have a question about the wrapping of JTextPanes. I have JTextPane inside a JScrollPane, and the way wrapping works is a little weird. Basically I want something like in Word: when you add text if it is too long it wraps at the next word. I know this is the default function of a JTextPane. When there isn't a word break, however, the JTextPane doesn't break the word in the middle of the word, but instead increases the size of the text pane (I think) to accommodate the larger word. This because the JTextPane is now bigger, any other text that I added earlier to the textpane which had previously word wrapped now extends to the new boundary of the textpane, and then wraps there.

    How can I make it so that if the word is too big for the textpane, instead of extending the textpane it cuts the word and puts the rest of the word on the next line?


  2. #2
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: How to enable wrapping in JTextPane

    I have not had my JTextPanes change size on me. Please consider creating and posting an SSCCE demonstrating your problem so that we can see it for ourselves, and perhaps be able to help you find a solution.

  3. #3
    Junior Member
    Join Date
    Dec 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to enable wrapping in JTextPane

    Ok, I have made a small program that demonstrates the problem. It is written using the Netbeans Swing editor, as is the program that has this same problem.

    If you run the program, when you type in the text field and press enter or press it adds the text to the text pane. If you just type normal length words, the wrapping works well. If you type 1 long word which is longer than the size of the text pane, however, it doesn't break at the end of the line but instead seems to increase the size of the text pane. If you had words that had wrapped before, now they wrap to the new boundary of the text pane. Now if you type words again into the text field and press send they also wrap to the new boundary.

    Is there any way to fix this?

    package testproject;
     
    import java.awt.Color;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledDocument;
     
    public class TextPaneExample extends javax.swing.JFrame {
        private StyledDocument chatDoc;
        private SimpleAttributeSet selfNameStyle;
        private SimpleAttributeSet messageNameStyle;
     
        public TextPaneExample() {
            initComponents();
     
            selfNameStyle = new SimpleAttributeSet();
            StyleConstants.setForeground(selfNameStyle, Color.RED);
            StyleConstants.setBold(selfNameStyle, true);
     
            messageNameStyle = new SimpleAttributeSet();
     
            chatDoc = chatTextPane.getStyledDocument();
        }
     
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
     
            sendField = new javax.swing.JTextField();
            sendButton = new javax.swing.JButton();
            chatScrollPane = new javax.swing.JScrollPane();
            chatTextPane = new javax.swing.JTextPane();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            sendField.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    sendFieldActionPerformed(evt);
                }
            });
     
            sendButton.setText("Send");
            sendButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    sendButtonActionPerformed(evt);
                }
            });
     
            chatTextPane.setEditable(false);
            chatScrollPane.setViewportView(chatTextPane);
     
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(chatScrollPane)
                        .add(layout.createSequentialGroup()
                            .add(sendField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(sendButton)))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .add(chatScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                        .add(sendField)
                        .add(sendButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                    .addContainerGap())
            );
     
            pack();
        }// </editor-fold>
     
        private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {
            sendMessage();
        }
     
        private void sendFieldActionPerformed(java.awt.event.ActionEvent evt) {
            sendMessage();
        }
     
        private void sendMessage() {
            String txt = sendField.getText();
            if (!txt.equals("")) {
                try {
                    chatDoc.insertString(chatDoc.getLength(), "You: ", selfNameStyle);
                    chatDoc.insertString(chatDoc.getLength(), txt + "\n", messageNameStyle);
                } catch(Exception e) {
                    System.err.println(e);
                }                
                sendField.setText("");
            }
        }
     
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(TextPaneExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(TextPaneExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(TextPaneExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(TextPaneExample.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
     
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TextPaneExample().setVisible(true);
                }
            });
        }
     
        // Variables declaration - do not modify
        private javax.swing.JScrollPane chatScrollPane;
        private javax.swing.JTextPane chatTextPane;
        private javax.swing.JButton sendButton;
        private javax.swing.JTextField sendField;
        // End of variables declaration
     
    }

  4. #4
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: How to enable wrapping in JTextPane

    Quote Originally Posted by kcaz View Post
    Ok, I have made a small program that demonstrates the problem. It is written using the Netbeans Swing editor, as is the program that has this same problem.

    If you run the program, when you type in the text field and press enter or press it adds the text to the text pane. If you just type normal length words, the wrapping works well. If you type 1 long word which is longer than the size of the text pane, however, it doesn't break at the end of the line but instead seems to increase the size of the text pane. If you had words that had wrapped before, now they wrap to the new boundary of the text pane. Now if you type words again into the text field and press send they also wrap to the new boundary.

    Is there any way to fix this?
    The funny thing is, that when I run your code, I don't run into this problem. If I type in a long sentence, it wraps well, and then if I type in a single very long word, it breaks the word at the edge of the textcomponent, and the previously well-wrapped sentence remains displayed unchanged with its wrap point remaining unchanged.

  5. #5
    Junior Member
    Join Date
    Dec 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to enable wrapping in JTextPane

    When you run it, does the very long word wrap to the next line, or is it just cut off?

  6. #6
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: How to enable wrapping in JTextPane

    Quote Originally Posted by kcaz View Post
    When you run it, does the very long word wrap to the next line, or is it just cut off?
    It wraps to the next line. I'm using Windows 7.0, and am running this with Java 1.7.

  7. #7
    Junior Member
    Join Date
    Dec 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to enable wrapping in JTextPane

    That's so weird. Right now I'm running on Ubuntu with Java 1.7, but I get the same problem when I run it on Windows 7 with Java 1.7. Do you have any idea why they would be different?

  8. #8
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: How to enable wrapping in JTextPane

    I wish I did -- sorry!

Similar Threads

  1. Java to HTML, enable user to enter a number of menu items
    By @passat in forum What's Wrong With My Code?
    Replies: 4
    Last Post: December 3rd, 2012, 08:42 AM
  2. MultiSet - Enable assertions.
    By kiiliikii in forum What's Wrong With My Code?
    Replies: 7
    Last Post: December 9th, 2011, 06:34 PM
  3. JTextPane questions.
    By sunde in forum AWT / Java Swing
    Replies: 1
    Last Post: March 28th, 2011, 03:18 PM
  4. Java JTextPane Save
    By ikurtz in forum File I/O & Other I/O Streams
    Replies: 9
    Last Post: April 28th, 2010, 01:02 AM
  5. how to enable tombol
    By ndoe in forum AWT / Java Swing
    Replies: 0
    Last Post: August 13th, 2009, 08:21 AM