JTextPane :  WordWrap again!!

Hi,
I know this a known problem, but maybe someone can still help:
JTextPane automatically wraps the text in it, and it looks quite horrible when you try to use it for programming purpuses..
Is there a way to turn off word wrapping in JTextPane ?????
Thanks

Thanks Gil,
I was just looking for an answer fo the same problem! - You should reward yourself!!!
Adaya.
P.S - If anybody has a more elegant answer please post it!

Similar Messages

  • How to get exact height of HTML line with SUB tag in JTextPane?

    Hi, this is my first post. I`ve been searching forum for an answer for a week, but didn`t find one.
    I have HTMLDocument inside JTextPane(exacty inside my class that extends it - MyTextPane). I want to do some custom painting in JTextPane so I need to be able to know exact pixel witdh for each line in the document. Easy except one thing, when I use SUB tag the width of the line cannot be simply calculated using FontMetrics, because I don`t know if the text inside SUB tag has lower font size and I don`t know its Y offset to normal line.
    I tried get these information from HTMLDocument using attributes from leafElements representing lines, but there seems to be a problem too.
    I pass this text:
    "(1) Line<SUB>jW</SUB><BR>(2) TextB"
    to setText method of MyTextPane, this method is overriden so it changes text Font
    public void setText(String s) {   
      super.setText(s);   
      setJTextPaneFont(this, new Font("Arial",Font.PLAIN,36), Color.black);
    }This is how the Element Structure looks like:
    Format is Element +": "+elementText+"|"+fontFamily+" "+fontSize
    BranchElement(html) 0,22: \n(1)?LinejW (2)?TextB\n|Monospaced 12
    ---BranchElement(head) 0,1: \n|Monospaced 12
    ------BranchElement(p-implied) 0,1: \n|Monospaced 12
    ---------LeafElement(content) 0,1: \n|Arial 36
    ---BranchElement(body) 1,22: (1) LinejW (2) TextB\n|Monospaced 12
    ------BranchElement(p-implied) 1,22: (1) LinejW (2) TextB\n|Monospaced 12
    ---------LeafElement(content) 1,9: (1) Line|Arial 36
    ---------LeafElement(content) 9,11: jW|Arial 36 <-----------THIS IS THE LOWER INDEX
    ---------LeafElement(content) 11,12: |Arial 36 <-----------THIS IS just space character '\u020'
    ---------LeafElement(content) 12,21: (2) TextB|Arial 36
    ---------LeafElement(content) 21,22: \n|Arial 36
    The height of Arial 36 is according to FontMetrics 43(and it really is), but height of the lowerIndex is just 40 pixels(on the screen), not 43 as I would expect. And I still dont have offset, where does the lower index starts paint itself.
    Is there any problem with my setText method, so that it changes font style for LOWER INDEX?
    I am using JTextPane as notEditable, with just one font style for entire document.
    Any suggestion?

    Is there any other way to get these information. I just found that I need that information before I put text it in the document.
    For example I am would like to generate lines:
    paragraph1 - text1
                             text2
    paragraph2 - text1
                             text2
                             text3
    paragraph3<SUB>some note</SUB> - text1
                                                                           text2
    normal text line
    I know what font line will be and I know its AttributeSet. I am trying to get appropriate number of spaces (or left indent) for text2,text3...lines. Then I will pass that string to setText method of JTextPane.
    I am unable to get appropriate width for "paragraph3<SUB>some note</SUB> - ", since text in SUB tag uses probably different font size.
    I am really sorry to bother again. I will think twice what I need before I posting.
    You`ve been very helpful so far Stas.
    Thanks.

  • Display image in JTextPane (JEditorPane)

    I'm writing an application with JTable and a JTextPane. When selecting a column in the JTable, I want to display the image associated with the selected row in the JTextPane.
    This wouldn't be a problem if the darn JTextPane would just display JUST AN IMAGE. But a JTextPane only displays an image if its embedded in an HTML file. Ugh. That would mean I'd have to create an html file for each picture. Ugh again.
    Is there any way around this?

    Nevermind, figured it out. Just have to use setText instead of setPage.
    htmlPane.setText("<IMG src='"+url+"'>");instead of:
    htmlPane.setPage(url);

  • Multi-line JTextPane: My SSCCE works, but not my reg. code . [LONG, sorry.]

    So, I'm trying to code this flash cards program, and it's not working. The problem is that, when I change the text of the JTextPane to have multiple lines, the text disappears, and my JTextPane acts like it's empty. I included my SSCCE as a comparison, because it works just fine. I hope you guys don't mind that I included all of the code for my Cards program, even the stuff that I know isn't relevant, but I'm at a loss, and it's bedtime, so I'm done editing for the night. If you guys can fix my code, feel free to use it for your own personal use (as a reward for having to deal with the irrelevant stuff). How do I get my text to appear when it has multiple lines?
    PS I know my button listeners aren't like they should be. I'm going to fix them after I fix the JTextPane.
    PPS If this breaks anyone's browser, I'm sorry, but I included a file that is format-dependent, so I had to include it as is. Also, I had to include tabs and not spaces because of the length limit.
    package sscce;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextPane;
    import javax.swing.WindowConstants;
    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;
    public class SSCCE
         private final Font     bold          = new Font("Courier New", Font.BOLD, 12),
              plain = new Font("Courier New", Font.PLAIN, 12);
         JButton                    button          = new JButton("Press this button");
         final JLabel          labels[]     = {new JLabel("xyz"), new JLabel("xyz"),
              new JLabel("xyz"), new JLabel("xyz"), new JLabel("xyz"),
              new JLabel("xyz")               };
         final String          oldText          = "This text should wrap automatically because it is long.",
              newText = "This text should add height to the textPane because it is longer than the original.";
         boolean                    textSwitch     = true;
         final JTextPane          tp               = createTextPane();
         final JPanel          upperPanel     = new JPanel(new GridLayout(3, 1)),
              lowerPanel = new JPanel(new GridBagLayout());
         private SSCCE()
              final JFrame frame = new JFrame("SSCCE");
              button.addActionListener(new ButtonListener());
              start();
              frame.add(upperPanel, BorderLayout.CENTER);
              frame.add(lowerPanel, BorderLayout.SOUTH);
              frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              frame.setSize(485, 338);
              frame.setVisible(true);
         public static void main(final String args[])
              new SSCCE();
         private void addItem(final String cell, final int colSpan,
              final int rowSpan, final JPanel pan)
              addItem(cell, colSpan, rowSpan, pan, new JLabel(" "), plain);
         private void addItem(final String cell, final int colSpan,
              final int rowSpan, final JPanel pan, final JComponent c, final Font f)
              final GridBagConstraints gc =
                   new GridBagConstraints(cell.charAt(0) - 65, cell.charAt(1) - 49,
                        colSpan, rowSpan, 100, 100, GridBagConstraints.CENTER,
                        GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0);
              try
                   pan.setFont(f);
                   pan.add(c, gc);
                   pan.validate();
              catch (final Exception e)
                   e.printStackTrace();
                   System.exit(0);
         private JTextPane createTextPane()
              final StyleContext context = new StyleContext();
              final StyledDocument document = new DefaultStyledDocument(context);
              final Style style = context.getStyle(StyleContext.DEFAULT_STYLE);
              final JTextPane textPane = new JTextPane(document);
              textPane.setText(oldText);
              StyleConstants.setAlignment(style, StyleConstants.ALIGN_CENTER);
              textPane.setFont(new Font("Courier New", Font.BOLD, 12));
              textPane.setEditable(false);
              return textPane;
         private void start()
              upperPanel.setBackground(Color.WHITE);
              upperPanel.setLayout(new GridLayout(3, 1));
              lowerPanel.setLayout(new GridBagLayout());
              final JPanel topPanel = new JPanel(new GridBagLayout()), middlePanel =
                   new JPanel(new GridBagLayout()), bottomPanel =
                   new JPanel(new GridBagLayout());
              topPanel.setBackground(Color.RED);
              middlePanel.setBackground(Color.GREEN);
              bottomPanel.setBackground(Color.BLUE);
              upperPanel.setBackground(Color.BLACK);
              addItem("A1", 1, 1, topPanel);
              addItem("A2", 1, 1, topPanel, new JLabel("test1"), plain);
              addItem("A3", 1, 1, topPanel);
              addItem("A1", 1, 1, middlePanel);
              addItem("A2", 1, 1, middlePanel, tp, bold);
              addItem("A3", 1, 1, middlePanel);
              addItem("A1", 1, 1, bottomPanel);
              addItem("A2", 1, 1, bottomPanel, new JLabel("test2"), plain);
              addItem("A3", 1, 1, bottomPanel);
              addItem("A1", 1, 1, lowerPanel);
              addItem("B1", 1, 1, lowerPanel, button, plain);
              addItem("C1", 1, 1, lowerPanel);
              upperPanel.add(topPanel);
              upperPanel.add(middlePanel);
              upperPanel.add(bottomPanel);
         private class ButtonListener implements ActionListener
              @Override
              public void actionPerformed(final ActionEvent arg0)
                   if (textSwitch)
                        tp.setText(newText);
                   else
                        tp.setText(oldText);
                   textSwitch = !textSwitch;
    package fc;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.KeyboardFocusManager;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.util.Arrays;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JTextPane;
    import javax.swing.WindowConstants;
    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;
    public class Cards implements ActionListener, FocusListener
         private Cards          allDefs[]          = null;
         private final Font     bold               = new Font("Courier New", Font.BOLD, 12),
              plain = new Font("Courier New", Font.PLAIN, 12);
         private JButton          button1               = null;
         private JButton          button2               = null;
         private final int     card               = 0;
         private final int     CE                    = GridBagConstraints.CENTER,
              E = GridBagConstraints.EAST, W = GridBagConstraints.WEST;
         private boolean          clickedWrong     = true;
         private String          course               = null, def = null, page = null,
              word = null;
         private JLabel          courseLabel          = null;
         private Cards          currDef               = null;
         private JTextArea     enterDefn          = null, enterWord = null;
         private JFrame          frame               = null;
         private JButton          invis               = null;
         private JButton          learn               = null;
         private boolean          message               = true;
         private JPanel          p[]                    = null;
         private JLabel          pageLabel          = null;
         private JPanel          panel[]               = null;
         private JTextArea     rightDefn          = null;
         private JTextArea     rightWord          = null;
         private Cards          saveDefs[]          = null;
         private JTextPane     showLabel          = null;
         private JLabel          sizeLabel          = null;
         public Cards()
              try
                   panel = new JPanel[2];
                   panel[0] = new JPanel();
                   panel[1] = new JPanel();
                   panel[0].removeAll();
                   panel[1].removeAll();
                   panel[0].revalidate();
                   panel[1].revalidate();
                   allDefs = populate();
                   button1 = new JButton();
                   button2 = new JButton();
                   learn = new JButton("Learn");
                   button1.addActionListener(this);
                   button2.addActionListener(this);
                   learn.addActionListener(this);
                   courseLabel = new JLabel();
                   pageLabel = new JLabel();
                   showLabel = createTextPane();
                   sizeLabel = new JLabel();
                   cardSetup();
                   panel[0].setBackground(Color.WHITE);
                   panel[1].setBackground(Color.WHITE);
                   panel[0].setBorder(null);
                   panel[1].setBorder(null);
                   frame = new JFrame("Flash Cards");
                   frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                   frame.setSize(485, 338);
                   frame.setLocationRelativeTo(null);
                   frame.add(panel[0], BorderLayout.CENTER);
                   frame.add(panel[1], BorderLayout.SOUTH);
                   frame.setResizable(false);
                   frame.setVisible(true);
                   start();
              catch (final Exception e)
                   e.printStackTrace();
         public Cards(final String defCourse, final String defWord,
              final String defDef, final String defPage)
              course = defCourse;
              word = defWord;
              def = defDef;
              page = defPage;
         public static void main(final String args[])
              new Cards();
         @Override
         public void actionPerformed(final ActionEvent e)
              final Object src = e.getSource();
              if (src == button1)
                   if (button1.getText().equals("Guess"))
                        button1.setText("Right");
                        button2.setText("Wrong");
                        showLabel.setText(currDef.def);
                        showLabel.setFont(bold);
                        panel[0].revalidate();
                        panel[1].revalidate();
                   else
                        allDefs = remDef(allDefs, card);
                        if (allDefs != null)
                             button1.setText("Guess");
                             button2.setText("Skip");
                             showCard();
                        else
                             if (saveDefs == null)
                                  frame.setVisible(false);
                                  if (JOptionPane
                                       .showConfirmDialog(
                                            null,
                                            "According to you, you have guessed all the words right. Would you like to start over?",
                                            "All Correct!", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
                                       allDefs = populate();
                                       start();
                                  else
                                       System.exit(0);
                             else
                                  button1.setText("Guess");
                                  button2.setText("Skip");
                                  allDefs = Arrays.copyOf(saveDefs, saveDefs.length);
                                  saveDefs = null;
                                  if (clickedWrong)
                                       clickedWrong = false;
                                       JOptionPane
                                            .showMessageDialog(
                                                 null,
                                                 "You are now going over terms that you said you guessed wrong.",
                                                 "", JOptionPane.INFORMATION_MESSAGE);
                                  showCard();
              else if (src == learn)
                   saveDefs = addDef(saveDefs, allDefs[card]);
                   allDefs = remDef(allDefs, card);
                   if (allDefs == null)
                        allDefs = Arrays.copyOf(saveDefs, saveDefs.length);
                        saveDefs = null;
                        if (clickedWrong)
                             clickedWrong = false;
                             JOptionPane
                                  .showMessageDialog(
                                       null,
                                       "You are now going over terms that you said you guessed wrong.",
                                       "", JOptionPane.INFORMATION_MESSAGE);
                   panel[0].removeAll();
                   panel[1].removeAll();
                   button1.setText("Guess");
                   button2.setText("Skip");
                   cardSetup();
                   showCard();
              else
                   if (button2.getText().equals("Wrong"))
                        int rows = 0;
                        final int colsWord = wordWrapWidth(allDefs[card].word, 21), colsDef =
                             67 - colsWord;
                        System.out.println(colsWord);
                        invis = new JButton("");
                        invis.setBackground(Color.BLACK);
                        p = new JPanel[3];
                        p[0] = new JPanel();
                        p[1] = new JPanel();
                        p[2] = new JPanel();
                        panel[0].setBackground(Color.BLACK);
                        rightWord = createTextArea(colsWord, allDefs[card].word);
                        rightDefn = createTextArea(colsDef, allDefs[card].def);
                        enterWord = createTextArea(colsWord);
                        enterDefn = createTextArea(colsDef);
                        enterWord.setBackground(Color.WHITE);
                        enterWord.setEditable(true);
                        enterWord.setFocusable(true);
                        p[0].setBackground(Color.BLACK);
                        p[1].setBackground(Color.BLACK);
                        p[2].setBackground(Color.BLACK);
                        p[0].add(rightWord);
                        p[0].add(rightDefn);
                        p[1].add(enterWord);
                        p[1].add(enterDefn);
                        p[2].add(invis); // otherwise invis appears when the word shows
                                                 // up
                        panel[0].removeAll();
                        panel[1].removeAll();
                        panel[0].revalidate();
                        panel[1].revalidate();
                        learn.setEnabled(false);
                        rightWord.setEditable(false);
                        rightDefn.setEditable(false);
                        rightWord.setBackground(Color.GREEN);
                        rightDefn.setBackground(Color.GREEN);
                        panel[0].setLayout(new GridBagLayout());
                        panel[1].setLayout(new GridBagLayout());
                        addItem("A1", 3, 1, panel[0], p[0], bold, CE, 100, 0,
                             GridBagConstraints.BOTH);
                        addItem("A2", 3, 1, panel[0], p[1], bold, CE, 100, 100,
                             GridBagConstraints.BOTH);
                        addItem("A3", 3, 1, panel[0], p[2], bold, CE, 100, 0,
                             GridBagConstraints.BOTH);
                        addItem("A1", 1, 1, panel[1], new JLabel(" "), plain, W);
                        addItem("B1", 1, 1, panel[1], learn, plain, CE);
                        addItem("C1", 1, 1, panel[1], sizeLabel, plain, E);
                        panel[0].revalidate();
                        panel[1].revalidate();
                        try
                             Thread.sleep(50);
                        catch (final Exception i)
                             i.printStackTrace();
                        rows =
                             Math.max(wordWrapLines(rightWord), wordWrapLines(rightDefn));
                        rightWord.setRows(rows);
                        rightDefn.setRows(rows);
                        enterWord.setRows(rows);
                        enterDefn.setRows(rows);
                        enterWord.requestFocus();
         public Cards[] addDef(final Cards array[], final Cards defined)
              Cards newarray[] = null;
              if (array == null)
                   newarray = new Cards[1];
              else
                   newarray = Arrays.copyOf(array, array.length + 1);
              newarray[newarray.length - 1] = defined;
              return newarray;
         public void addItem(final String cell, final int colSpan,
              final int rowSpan, final JPanel pan)
              addItem(cell, colSpan, rowSpan, pan, new JLabel(" "), plain, E);
         public void addItem(final String cell, final int colSpan,
              final int rowSpan, final JPanel pan, final JComponent c, final Font f,
              final int anchor)
              addItem(cell, colSpan, rowSpan, pan, c, f, anchor, 100, 100);
         public void addItem(final String cell, final int colSpan,
              final int rowSpan, final JPanel pan, final JComponent c, final Font f,
              final int anchor, final int weightx, final int weighty)
              addItem(cell, colSpan, rowSpan, pan, c, f, anchor, weightx, weighty,
                   GridBagConstraints.NONE);
         public void addItem(final String cell, final int colSpan,
              final int rowSpan, final JPanel pan, final JComponent c, final Font f,
              final int anchor, final int weightx, final int weighty, final int fill)
              final GridBagConstraints gc =
                   new GridBagConstraints(cell.charAt(0) - 65, cell.charAt(1) - 49,
                        colSpan, rowSpan, weightx, weighty, anchor, fill, new Insets(0,
                             0, 0, 0), 0, 0);
              if (f != null)
                   c.setFont(f);
              try
                   pan.add(c, gc);
                   pan.validate();
              catch (final Exception e)
                   e.printStackTrace();
                   System.exit(0);
         public void addItem(final String cell, final int colSpan,
              final int rowSpan, final JPanel pan, final JComponent c,
              final int anchor, final int weighty, final int weightx)
              final GridBagConstraints gc =
                   new GridBagConstraints(cell.charAt(0) - 65, cell.charAt(1) - 49,
                        colSpan, rowSpan, weighty, weightx, anchor,
                        GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0);
              try
                   pan.add(c, gc);
                   pan.validate();
              catch (final Exception e)
                   e.printStackTrace();
                   System.exit(0);
         public void cardSetup()
              panel[0].setBackground(Color.WHITE);
              panel[0].setLayout(new GridLayout(3, 1));
              panel[1].setLayout(new GridBagLayout());
              final JPanel topPanel = new JPanel(new GridBagLayout()), middlePanel =
                   new JPanel(new GridBagLayout()), bottomPanel =
                   new JPanel(new GridBagLayout());
              middlePanel.setBackground(Color.GREEN);
              addItem("A1", 1, 3, topPanel);
              addItem("B1", 1, 2, topPanel);
              addItem("C1", 1, 1, topPanel);
              addItem("C2", 1, 1, topPanel, courseLabel, plain, E);
              addItem("C3", 1, 1, topPanel);
              addItem("A1", 1, 1, middlePanel, new JLabel(" "), bold, CE);
              addItem("A2", 1, 1, middlePanel, showLabel, bold, CE);
              addItem("A3", 1, 1, middlePanel, new JLabel(" "), bold, CE);
              addItem("A1", 1, 1, bottomPanel);
              addItem("B2", 1, 1, bottomPanel, pageLabel, plain, E);
              addItem("A3", 1, 1, bottomPanel);
              addItem("A1", 1, 1, panel[1]);
              addItem("B1", 1, 1, panel[1], button1, plain, E);
              addItem("C1", 1, 1, panel[1], button2, plain, W);
              addItem("D1", 1, 1, panel[1], sizeLabel, bold, E);
              panel[0].add(topPanel);
              panel[0].add(middlePanel);
              panel[0].add(bottomPanel);
         public JTextArea createTextArea(final int cols)
              return createTextArea(cols, "");
         public JTextArea createTextArea(final int cols, final String text)
              final JTextArea t = new JTextArea(text, 1, cols);
              t.addFocusListener(this);
              t.setBackground(Color.LIGHT_GRAY);
              t.setEditable(false);
              t.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
                   null);
              t.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
                   null);
              t.setFocusable(false);
              t.setFont(bold);
              t.setLineWrap(true);
              t.setWrapStyleWord(true);
              t.setSize(0, Short.MAX_VALUE);
              return t;
         private JTextPane createTextPane()
              final StyleContext context = new StyleContext();
              final StyledDocument document = new DefaultStyledDocument(context);
              final Style style = context.getStyle(StyleContext.DEFAULT_STYLE);
              final JTextPane textPane = new JTextPane(document);
              textPane
                   .setText("This text should wrap automatically because it is long.");
              StyleConstants.setAlignment(style, StyleConstants.ALIGN_CENTER);
              textPane.setFont(new Font("Courier New", Font.BOLD, 12));
              textPane.setEditable(false);
              textPane.setBorder(BorderFactory.createLineBorder(Color.RED));
              return textPane;
         @Override
         public void focusGained(final FocusEvent e)
              final JTextArea src = (JTextArea) e.getSource();
              src.setBackground(Color.WHITE);
              src.setCaretPosition(0);
              src.setEditable(true);
         @Override
         public void focusLost(final FocusEvent e)
              final JTextArea src = (JTextArea) e.getSource();
              boolean correct = false;
              if (src == enterWord)
                   correct = src.getText().equals(rightWord.getText());
              else if (src == enterDefn)
                   correct = src.getText().equals(rightDefn.getText());
              if (correct)
                   src.setBackground(Color.GREEN);
                   src.setEditable(false);
                   if (src == enterWord)
                        enterDefn.setFocusable(true);
                        enterDefn.setEditable(true);
                        enterDefn.requestFocus();
                   if (src == enterDefn)
                        invis.setFocusable(false);
                        learn.setEnabled(true);
                        learn.requestFocus();
              else
                   if (message)
                        if (src == enterWord)
                             int rightChars = 0;
                             for (int c = 0; c < rightWord.getText().length()
                                  && c < src.getText().length(); c++)
                                  if (rightWord.getText().charAt(c) != src.getText()
                                       .charAt(c))
                                       break;
                                  rightChars++;
                             JOptionPane.showMessageDialog(
                                  null,
                                  rightWord.getText().substring(0, rightChars)
                                       + "|"
                                       + rightWord.getText().substring(rightChars,
                                            rightWord.getText().length())
                                       + "\n"
                                       + src.getText().substring(0, rightChars)
                                       + "|"
                                       + src.getText().substring(rightChars,
                                            src.getText().length()), "Incorrect",
                                  JOptionPane.ERROR_MESSAGE);
                        if (src == enterDefn)
                             int rightChars = 0;
                             for (int c = 0; c < rightDefn.getText().length()
                                  && c < src.getText().length(); c++)
                                  if (rightDefn.getText().charAt(c) != src.getText()
                                       .charAt(c))
                                       break;
                                  rightChars++;
                             JOptionPane.showMessageDialog(
                                  null,
                                  rightDefn.getText().substring(0, rightChars)
                                       + "|"
                                       + rightDefn.getText().substring(rightChars,
                                            rightDefn.getText().length())
                                       + "\n"
                                       + src.getText().substring(0, rightChars)
                                       + "|"
                                       + src.getText().substring(rightChars,
                                            src.getText().length()), "Incorrect",
                                  JOptionPane.ERROR_MESSAGE);
                        src.requestFocus();
                   message = !message;
         public Cards[] populate()
              Cards c[] = null;
              try
                   final File file = new File("FC.txt");
                   if (file.exists())
                        final BufferedReader in =
                             new BufferedReader(new FileReader(file));
                        String line = null;
                        int badTerms = 0, goodTerms = 0;
                        while ((line = in.readLine()) != null)
                             final String lines[] = line.split("\t");
                             if (lines.length == 4)
                                  c =
                                       addDef(c, new Cards(lines[0], lines[1], lines[2],
                                            lines[3]));
                                  goodTerms++;
                             else
                                  badTerms++;
                        if (badTerms > 0)
                             JOptionPane
                                  .showMessageDialog(
                                       null,
                                       "There were "
                                            + badTerms
                                            + " bad term(s) and "
                                            + goodTerms
                                            + " good term(s). You will see only the good entries for the terms.",
                                       "There were bad terms.",
                                       JOptionPane.INFORMATION_MESSAGE);
                   else
                        JOptionPane
                             .showMessageDialog(
                                  null,
                                  "The file "
                                       + file.getCanonicalPath()
                                       + " does not exist. Please download the file or create it, and then restart the program.",
                                  "File Not Found", JOptionPane.ERROR_MESSAGE);
                        System.exit(0);
              catch (final Exception e)
                   e.printStackTrace();
              return c;
         public void printTA(final JTextArea ta)
              System.out.println("cols=" + ta.getColumns());
              System.out.println("rows=" + ta.getRows());
              System.out.println("text=" + ta.getText());
              System.out.println("getText.length()=" + ta.getText().length());
         public Cards[] remDef(final Cards[] array, final int cardnum)
              Cards temp[] = null;
              if (array.length > 1)
                   temp = new Cards[array.length - 1];
                   int defLength = 0;
                   for (int l = 0; l < array.length; l++)
                        if (!array[cardnum].equals(array[l]))
                             temp[defLength] = array[l];
                        else
                             defLength--;
                        defLength++;
              return temp;
         private void showCard()
              currDef = allDefs[(int) Math.floor(Math.random() * allDefs.length)];
              courseLabel.setText(currDef.course);
              pageLabel.setText(currDef.page);
              showLabel.setText(currDef.word);
              sizeLabel.setText("Left: " + allDefs.length);
         private void start()
              button1.setText("Guess");
              button2.setText("Skip");
              showCard();
              frame.setVisible(true);
         @Override
         public String toString()
              return "Java.lang.Cards[" + course + "," + word + "," + def + ","
                   + page + "]";
         public String wordWrap(final String string, final int w)
              String newStr = "", s = string;
              final int width = w;
              int oldSpace = 0;
              if (s.length() < w)
                   return s;
              for (int c = 0; c < s.length(); c++)
                   if (c == s.length() - 1)
                        if (s.length() > width && oldSpace != 0)
                             newStr +=
                                  s.substring(0, oldSpace).replace("(", "\\(")
                                       .replace(")", "\\)")
                                       + "<br/>" + s.substring(oldSpace + 1, s.length());
                        else
                             newStr += s;
                   else if (s.charAt(c) == ' ')
                        if (c > width)
                             newStr += s.substring(0, oldSpace) + "<br/>";
                             s =
                                  s.replaceFirst(
                                       s.substring(0, oldSpace).replace("(", "\\(")
                                            .replace(")", "\\)")
                                            + " ", "");
                             c = 0;
                        oldSpace = c;
              return newStr;
         private int wordWrapLines(final JTextArea t)
              return wordWrap(t.getText(), t.getColumns()).replaceAll("<br/>", "\n")
                   .split("\n").length;
         private int wordWrapWidth(final String s, final int w)
              final String lines[] =
                   wordWrap(s, w).replaceAll("<br/>", "\n").split("\n");
              int maxWidth = 0;
              for (final String line : lines)
                   if (line.length() > maxWidth)
                        maxWidth = line.length();
              if (maxWidth > w)
                   return w;
              return maxWidth;
    }And here is the accompanying file for Cards.java
    ET115     accuracy     the difference between the measured and accepted or "true" value of a measurement     01.04.013.2
    ET115     ampere-hour rating     a number given in ampere-hours; determined by multiplying a current in amps times the length of time in hours a battery can deliver that current to a load     03.07.093.1
    ET115     atom     the smallest element particle that possesses the unique characteristics of that element     02.01.024.1
    ET115     battery     an energy source that uses a chemical reaction to convert chemical energy into electrical energy     02.03.031.1
    ET115     charge     an electrical property of matter that exists because of an excess or deficiency of electrons     02.02.028.1
    ET115     circuit     an interconnection of a source, a load, and an interconnecting current path that are designed produce a desired result     02.06.047.1
    ET115     circuit breaker     a resettable protective device used for interrupting excessive current in an electric circuit     02.06.050.2
    ET115     colour code     a system of colour bands or dots that identify the vale of a resistor or other component     02.05.040.2
    ET115     conductance     the ability of a circuit to allow current; the reciprocal of resistance     02.05.038.3
    ET115     conductor     a material in which electrical current is established with relative ease     02.01.027.1
    ET115     coulomb     the unit of electrical charge; the total charge possessed by 6.25 * 10^18 electrons     02.02.028.2
    ET115     DMM     digital multimeter; an electronic instrument that combines meters for the measurement of voltage, current, and resistance     02.07.057.1
    ET115     electronic     related to the movement and control of free electrons in semiconductors or vacuum devices     02.01.027.3
    ET115     engineering notation     a system for representing any number as a one-, two-, or three-digit number, times a power of ten with an exponent that is a multiple of 3     01.01.007.1
    ET115     error     the difference between the true measured and best-accepted value of a measurement     01.04.013.1
    ET115     free electron     a valence electron that has broken away from its parent atom and is free to move from atom to atom within the atomic structure of a material     02.01.026.1
    ET115     fuse     a protective device that burns open when there is excessive current in a circuit     02.06.050.1
    ET115     half-splitting     a troubleshooting procedure where one starts in the middle of a circuit or system and, depending on the first measurement, works toward the output or toward the input to find the fault     03.08.096.1
    ET115     ion     an atom that has gained or lost a valence electron and resulted in a net positive or negative charge     02.01.026.2
    ET115     load     a resistor or other component that is connected across the output terminals of a circuit, draws current from the source, and has work done upon it     02.06.047.2
    ET115     metric prefix     a symbol that is used to replace the power of ten in numbers expressed in engineering notation     01.02.010.1
    ET115     Ohm's law     a law stating that current is directly proportional to voltage and inversely proportional to resistance     03.01.075.1
    ET115     orbit     the path an electron takes as it circles around the nucleus of an atom     02.01.025.2
    ET115     photovoltaic effect     the process where light energy converts directly into electrical energy     02.03.033.1
    ET115     piezoelectric effect     the property of a crystal where a changing mechanical stress produces a voltage across the crystal     02.03.034.2
    ET115     power of ten     a numerical representation consisting of a base 10 and an exponent; the number 10 raised to a power     01.01.004.2
    ET115     power rating     the maximum amount of power a resistor can dissipate without being damaged by excessive heat build-up     03.05.088.1
    ET115     precision     a measure of the repeatability or consistency of a series of measurements     01.04.013.3
    ET115     resistor     an electrical component designed specifically to have a certain amount of resistance     02.05.039.1
    ET115     round off     the process of dropping one or more digits to the right of the last significant digit in a number     01.04.015.1
    ET115     scientific notation     a system for representing any number as a number between 1 and 10 times an appropriate power of ten     01.01.004.1
    ET115     Seebeck effect     the generation of a voltage at the junction of two different metals that have a temperature difference between them     02.03.034.1
    ET115     semiconductor     a material that has a conductance value between that of a conductor and an insulator     02.01.027.2
    ET115     SI     standardised international system of units used for all engineering and scientific work; abbreviation for French Le Systeme International d'Unites     01.02.009.1
    ET115     switch     an electrical or electronic device for opening and closing a current path     02.06.048.4
    ET115     thermistor     a type of temperature transducer in which resistance is inversely proportional to temperature     02.05.046.2
    ET115     thermocouple     a thermoelectric type of voltage source that is commonly used to sense temperature     02.03.033.4
    ET115     troubleshooting     a systematic process of isolating, identifying, and correcting a fault in a circuit or system     03.08.095.1
    ET115     voltage     the amount of energy available to move a certain number of electrons from one point or another in an electrical circuit     02.03.029.Edited by: ElectrifiedBrain on Apr 12, 2011 12:08 AM

    EJP wrote:
    No way anybody in their right mind is going to look at all that. Find the salient differences between your SCCE and your non-working code.I didn't think so, but it was worth a shot. I did my best to find it last night, but I just couldn't.
    Kleopatra wrote:
    hahahaha ... you really think that'll work: "I'm tired, so going for a nap - hope you'll clean the mess and have it fixed when I wakeup"
    Dream well
    JeanetteIt was midnight, and I had to wake up at 5:30, so that was true. I didn't really think it was going to work, but I was hoping.
    Anyway, this can be locked too, I guess. I have an idea on how to find what's wrong.

  • Open a File in a JTextPane via Drag and Drop

    Hi,
         I have a simple JTextPane in a Swing App on Windows XP. I would like to know if it is possible for me to be able to add the functionality such that I can drag a text file to the JTextPane and it would open the file inside the Pane. Is this possible? If yes then how do I implement it? (I am not insisting on the app working on non-Win XP systems � so portability is not a concern.)
         I have tried to search for the drag and drop stuff but I am confused. First, which interfaces should I implement i.e. DragGestureListener, DragSourceListener, DropTargetListener or what?
         I would be grateful for any pointers.
    Thanks a lot,
    O.O.

    1. http://java.sun.com/docs/books/tutorial/uiswing/dnd/intro.html - This link did have the information but has since been updated and no longer points to the relevant information that I have since used.
    So you where given a link with the appropriate informaton, but Sun has changed the information and you are blaming us for not helping? Unbelievable!
    Here is a link to the old tutorial:
    https://www.cs.auckland.ac.nz/references/java/java1.5/tutorial/uiswing/dnd/intro.html#importFiles
    Now tell us how that does not do exactly what you wanted?
    I really don�t know why some people waste their time here just providing you with linksBecause most people like yourself don't know how to ask a question. DnD is a complex topic. The only way to learn it is to read a tutorial and experiment. What a better way to learn than to play with a working example. You are given many working examples in the tutorial.
    You did not state wihich example you had changed. You did not state what problems you where having.
    The best you could state was "I'm confused". You where asked to clarify your problem/confusion but didn't. We are not mind readers so we couldn't provide further help.
    I agree I am wasting my time helping someone who doesn't even appreciate the effort made by the many individuals of the forum and I won't make that mistake again.

  • In a Table trying to WordWrap a long string

    Using a single column and row table to post notes from a data run. The notes may be long and when using a constant font size the string goes off the page, hense the need for WordWrapping
    Attachments:
    Jims_Try.TDR ‏59 KB
    tdmtest.tdm ‏15 KB

    Hello Todd,
    I already spoke to you about this issue and sent you a modified TDR, but I thought that I'd answer it for anyone else who might be interested.
    You should instead use a "Text Object". It is located in the "Decorations" category in the "Report" view. Double-click on the oject to bring up the "Text Object Editor". Use "DIAdem expression >> new" to be able to access DIAdem channels, variables, and functions. I used the expression "cht(1,13)", for instance, to tell the report to load the text from channel 13 into the Text Oject. The Text Oject automatically wraps around.
    Thanks again for contacting National Instruments. Take care!
    Aaron B.
    National Instruments
    Attachments:
    Todds_Try_Modified.TDR ‏63 KB

  • Force word wrap in JTextPane (using HTMLEditorKit)

    Hi!
    I have a JTextPane on a JScrollPane inside a JPanel. My text pane is using HTMLEditorKit.
    I set the scrolling policies of my JScrollPane to: JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED & JScrollPane.HORIZONTAL_SCROLLBAR_NEVER.
    I did not find in JTextPane�s API any relevant property I can control word-wrapping with (similar to JTextArea�s setLineWrap) and I have tried a few things to force word-wrapping but nothing worked...
    What happens is my text is NOT being wrapped (even though there is no horizontal scrolling) and typed characters (it is an enabled editable text componenet) are being added to the same long line�
    I�d like to force word-wrapping (always) using the vertical scroll bar whenever the texts extends for more then one (wrapped) line.
    Any ideas?
    Thanks!!
    Message was edited by:
    io1

    Your suggestion of using the example only holds if it fits the requirements of the featureDid your questions state anywhere what your requirement was?
    You first questions said you had a problem, so I gave you a solution
    You next posting stated what your where currently doing, but it didn't say it was a requirement to do it that way. So again I suggested you change your code to match the working example.
    Finally on your third posting you state you have some server related issues causing the requirement which I did not know about in my first two postings.
    State your problem and special requirments up front so we don't waste time quessing.
    I've used code like this and it wraps fine:
    JTextPane textPane = new JTextPane();
    textPane.setContentType( "text/html" );
    HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit();
    HTMLDocument doc = (HTMLDocument)textPane.getDocument();
    textPane.setText( "<html><body>some long text ...</body></html>" );
    JScrollPane scrollPane = new JScrollPane( textPane );If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Horizontal scroll bar on JTextPane

    Hey everyone! I need to know how I can add a horizontal scroll bar to a jTextPane. I can NOT use a jTextArea though because I need to be using a StyledDocument. Right now, when I add it to a jScrollPane, it only scrolls vertically, but it wordwraps. Thanks for reading!

    Override getScrollableTracksViewportHeight() method to return false and at the same time, override setSize() method to adjust size of text pane. Following example shows this:
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    * TextPane without wrap.
    * @author mrityunjoy_saha
    * @version 1.0
    * @since Apex 1.2
    public class NoWrapTextPaneTest {
        private JTextPane editor;
        public NoWrapTextPaneTest() {
            JFrame frame = new JFrame("NoWrapTextPaneTest");
            frame.setSize(new Dimension(300, 400));
            //frame.setResizable(false);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.editor = new JTextPane() {
                @Override
                public boolean getScrollableTracksViewportWidth() {
                    return false;
                @Override
                public void setSize(Dimension d) {
                    Dimension pSize = getParent().getSize();
                    if (d.width < pSize.width) {
                        super.setSize(pSize.width, d.height);
                    } else {
                        super.setSize(d);
            frame.getContentPane().add(new JScrollPane(editor,
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
            frame.setVisible(true);
        public static void main(String[] args) {
            NoWrapTextPaneTest textPaneTest = new NoWrapTextPaneTest();
    } Thanks,
    Mrityunjoy

  • Is caret positioning in right-to-left oriented jtextpane corruptable?

    Dear all -
    Below is a serious problem. I hope I can get help from you experts out there; otherwise, I think it is a bug that should be reported to the JDK developers.
    I am writing an editor using my own keyboard layout to type in Arabic. To do so, I use jTextPane, and my own implementation of DocumentFilter (where I map English keys to Arabic letters). I start by i) setting the component orientation of jTextPane to be from RIGHT_TO_LEFT, and ii) attaching a caretListener to trace the caret's position.
    The problem (I think it is a bug just like what is recorded here: http://bugs.adobe.com/jira/browse/SDK-16315):
    Initially as I type text in Arabic, there is one-to-one correspondence between where I point my mouse and where the caret displays, basically, the same place. However, a problem occurs (and can always be re-produced) when I type a word towards the end of the line, follow it by a space character, and that space character causes the word to descend to the next line as a result of a wrap-around. Now, as I point my mouse to that first line again, the location where I click the mouse and the location where the caret flashes are no longer coincident! Also, the caret progression counter is reversed! That is, if there are 5 characters on Line 1, then whereas initially the caret starts from Position 0 on the right-hand side and increases as more text is added from right to left, it is now reversed where the the caret now increases from left to right for the first line, but correctly increases from right to left in the second line! yes funny stuff and very hard to describe to.
    So, here is an example. I wrote the code below (JDK1.6_u10, on Netbeans 6.5 RC2) to make it easy to reproduce the problem. In the example, I have replaced the keys A, S, D, F and G with their Arabic corresponding letters alif, seen, daal, faa and jeem. Now, type these letters inside the double quotes (without the double quotes) including the two spaces please and watch out for the output: "asdfg asdfg ". Up until you type the last g and before you type space, all is perfect, and you should notice that the caret position correctly moves from 0 upwards in the printlines I provided. When you type that last space, the second word descends as a result of the wrap-around, and hell breaks loose! Notice that whereas the mouse and caret position are coincident on the second line, there is no way to fine-control the mouse position on the first line any more. Further, whereas adding text on the second line is intuitive (i.e., you can insert more text wherever you point your mouse, which is also where the caret would show up), for the first line, if you point the mouse any place over the written string, the caret displays in a different place, the any added text is added in the wrong place! All this because the caret counter is now reversed, which should never occur. Any ideas or fixes?
    Thank you very much for reading.
    Mohsen
    package workshop.onframes;
    import java.awt.ComponentOrientation;
    import java.awt.Rectangle;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    import javax.swing.text.BadLocationException;
    public class NewJFrame1 extends javax.swing.JFrame {
    public NewJFrame1() {
    initComponents();
    jTextPane1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    CaretListener caretListener = new CaretListener() {
    public void caretUpdate(CaretEvent e) {
    int dot = e.getDot();
    int mark = e.getMark();
    if (dot == mark) {
    try {
    Rectangle cc = jTextPane1.modelToView(dot);
    System.out.println("Caret text position: " + dot +
    ", view location (x, y): (" + cc.x + ", " + cc.y + ")");
    } catch (BadLocationException ble) {
    System.err.println("CTP: " + dot);
    } else if (dot < mark) {
    System.out.println("Selection from " + dot + " to " + mark);
    } else {
    System.out.println("Selection from " + mark + " to " + dot);
    jTextPane1.addCaretListener(caretListener);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane3 = new javax.swing.JScrollPane();
    jTextPane1 = new javax.swing.JTextPane();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextPane1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
    jTextPane1.setAutoscrolls(false);
    jTextPane1.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(java.awt.event.KeyEvent evt) {
    jTextPane1KeyTyped(evt);
    jScrollPane3.setViewportView(jTextPane1);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)
    .addContainerGap())
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    private void jTextPane1KeyTyped(java.awt.event.KeyEvent evt) {
    if (evt.getKeyChar() == 'a') {
    evt.setKeyChar('\u0627');
    } else if (evt.getKeyChar() == 's') {
    evt.setKeyChar('\u0633');
    } else if (evt.getKeyChar() == 'd') {
    evt.setKeyChar('\u062f');
    } else if (evt.getKeyChar() == 'f') {
    evt.setKeyChar('\u0641');
    } else if (evt.getKeyChar() == 'g') {
    evt.setKeyChar('\u062c');
    public
    static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new NewJFrame1().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration
    }

    Hi Mohsen,
    I looked at it and indeed, I see what you describe. Sorry, but I can't shed any light. I tried to figure out what software component, or combination of components, is the cause of the problem. I see several candidates:
    1) The JTextPane
    2) The Document
    3) RTL support
    4) BIDI support
    5) Interpretation (by any other software component) of the left and right arrow key
    6) The font
    To clarify number 6: I know virtually nothing of Arabic language (apart from it being written from right to left). I remember however that the actual representation of a letter is dependent of its position between other letters: front, middle and end. What I see to my astonishment is that it seems that the rendering is also aware of this phenomenon. When you insert an A between the S and D of ASDFG, the shape of the S changes. Quite magic.
    I tried to add a second textpane with the same Document, but a different size, to see what would happen with number one if one types text in number two and vice versa.
    In my first attempt, the font that you set on textpane one was gone after I set its document to number two. For me that is very strange. The font was set to the textpane, not to the document. The separation betweem Model and View seems not very clear in this case. So I now also set that font on the second textpane.
    I will post the changed code so that you may experiment some more and hopefully will find the problem.
    You might be interested in a thread on java dot net forums that discusses a memory leak for RTL [http://forums.java.net/jive/message.jspa?messageID=300344#300344]
    Piet
    import java.awt.ComponentOrientation;
    import java.awt.EventQueue;
    import java.awt.Font;
    import java.awt.Rectangle;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.GroupLayout;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.WindowConstants;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    public class NewJFrame1 extends JFrame {
        private static final long serialVersionUID = 1L;
        public NewJFrame1() {
         initComponents();
         // jTextPane1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
         this.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
         CaretListener caretListener = new CaretListener() {
             public void caretUpdate(CaretEvent e) {
              int dot = e.getDot();
              int mark = e.getMark();
              if (dot == mark) {
                  try {
                   Rectangle cc = jTextPane1.modelToView(dot);
                   System.out.println("Caret text position: " + dot
                        + ", view location (x, y): (" + cc.x + ", "
                        + cc.y + ")");
                  } catch (BadLocationException ble) {
                   System.err.println("CTP: " + dot);
              } else if (dot < mark) {
                  System.out.println("Selection from " + dot + " to " + mark);
              } else {
                  System.out.println("Selection from " + mark + " to " + dot);
         jTextPane1.addCaretListener(caretListener);
        private KeyAdapter toArabic = new KeyAdapter() {
         public void keyTyped(KeyEvent evt) {
             jTextPane1KeyTyped(evt);
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
        // @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
         jScrollPane3 = new JScrollPane();
         jTextPane1 = new JTextPane();
         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
         jTextPane1.setFont(new Font("Tahoma", 0, 24)); // NOI18N
         jTextPane1.setAutoscrolls(false);
         jTextPane1.addKeyListener(toArabic);
         jScrollPane3.setViewportView(jTextPane1);
         GroupLayout layout = new GroupLayout(getContentPane());
         getContentPane().setLayout(layout);
         layout.setHorizontalGroup(layout.createParallelGroup(
              GroupLayout.Alignment.LEADING).addGroup(
              layout.createSequentialGroup().addContainerGap().addComponent(
                   jScrollPane3, GroupLayout.DEFAULT_SIZE, 159,
                   Short.MAX_VALUE).addContainerGap()));
         layout.setVerticalGroup(layout.createParallelGroup(
              GroupLayout.Alignment.LEADING).addGroup(
              layout.createSequentialGroup().addContainerGap().addComponent(
                   jScrollPane3, GroupLayout.PREFERRED_SIZE, 85,
                   GroupLayout.PREFERRED_SIZE).addContainerGap(
                   GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
         pack();
        }// </editor-fold>
        private void jTextPane1KeyTyped(KeyEvent evt) {
         if (evt.getKeyChar() == 'a') {
             evt.setKeyChar('\u0627');
         } else if (evt.getKeyChar() == 's') {
             evt.setKeyChar('\u0633');
         } else if (evt.getKeyChar() == 'd') {
             evt.setKeyChar('\u062f');
         } else if (evt.getKeyChar() == 'f') {
             evt.setKeyChar('\u0641');
         } else if (evt.getKeyChar() == 'g') {
             evt.setKeyChar('\u062c');
        public static void main(String args[]) {
         EventQueue.invokeLater(new Runnable() {
             public void run() {
              final NewJFrame1 frameOne = new NewJFrame1();
              frameOne.setLocationRelativeTo(null);
              frameOne.setVisible(true);
              EventQueue.invokeLater(new Runnable() {
                  public void run() {
                   Document doc = frameOne.jTextPane1.getDocument();
                   JTextPane textPane2 = new JTextPane();
                   textPane2.setFont(new Font("Tahoma", 0, 24)); // NOI18N
                   textPane2.setAutoscrolls(false);
                   textPane2.setDocument(doc);
                   textPane2.addKeyListener(frameOne.toArabic);
                   JFrame frameTwo = new JFrame();
                   frameTwo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frameTwo.add(new JScrollPane(textPane2));
                   frameTwo.setSize(400, 300);
                   frameTwo.setLocationByPlatform(true);
                   frameTwo.setVisible(true);
                   frameTwo
                        .applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        // Variables declaration - do not modify
        private JScrollPane jScrollPane3;
        private JTextPane jTextPane1;
        // End of variables declaration
    }

  • How can I copy and paste (styled) text in JTextPane/JEditorPane?

    I have a styled text in my editor and I use the copy and the paste action in JTextPane, but i am not able to paste again with previous text formatting(it inserts same text, but with logical attributes - formatting at caret/inserted/ position)
    I use RTFEditor kit.
    Is it possible to put information about styled text into clipboard and paste it back? Shall I simulate clipboard somehow?
    Please help
    Thanks for any suggestion
    Vity

    This [url http://forum.java.sun.com/thread.jsp?forum=57&thread=197091]thread contains a discussion on this topic with a few suggestions. I haven't tried them so I don't know how they work. I found the thread by searching the forum with the keywords "+copy +style +jtextpane".

  • JTextPane, how to set only a part of text editable?

    How to set only a part of text in JTextPane editable? For example I want to forbid changing text after 'enter'. JTextPane has method setEditable but this works only for whole JTextPane.
    Plz help!!!

    I'm working on some application similar to unix console. It can't be done relatively simply with the provided components (for example two textfileds), but then it will not look like console :) .
    Now some technical problems:
    Anyway, use a DocumentListener and have it ignore any changes
    in areas you deem to be protected.I have no idea how to ignore changes using DocumentListener. Could you give more information abut this?
    I found "my own way". I create MyDefaultStyledDocument which extends DefaultStyledDocument. Then I overwrite two methods: insertString and remove. Using offsets values I manage to block everything before " > ", and I protect output from editing. But I still have a problem:
    This works fine (add "> " to JTextPane text):
                String s = console.getText();
                s = s+"> ";
                console.setText(s); but this doesn't work (for example replace last word):
                    String all = parent.getText();
                    all = all.substring(0,all.length() - cut);
                    all = all+text+" ";
                    parent.setText(all);where: parent = console = JTextPane
    Why?
    And one more question. Why when I typed "enter", Document remove all text and paste it again :/

  • Insertion of icons into JTextPane

    Hello!
    I am trying to insert icons into JTextPane object, and I got a problem.
    My partial code is as follows...
    StyleConstants.setIcon(s, icnIcons);
    doc.insertString(doc.getLength(), "I", doc.getStyle("icon"));
    doc.insertString(doc.getLength(), "I", doc.getStyle("icon"));
    In the above code, s is an object of Style, and icnIcons is an object of ImageIcon, and doc is an object of StyledDocument.
    And the style, s, is registered with a name, "icon".
    If I execute the above code, then only one icon is displayed. But the length of the text is increased by 2.(I check this using doc.getLength() method.)
    So, I make a little change to the above code like the following:
    StyleConstants.setIcon(s, icnIcons);
    doc.insertString(doc.getLength(), "I\n", doc.getStyle("icon")); //changed
    doc.insertString(doc.getLength(), "I", doc.getStyle("icon"));
    I just add "\n". And the second code is working, and displays two icons.
    But the two icons are on the separate line.
    And if I use two different icons, that is, two different styles, in the first code segment, then it works and shows the two icons on the same line, though I didn't use the "\n".
    Why does this happen?
    I am so confused. Please help me.
    Thanks for every body!
    Regards

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.text.*;
    public class IconPane {
        private void showTest(BufferedImage[] images) throws IOException {
            JTextPane textPane = new JTextPane();
            // Add some content.
            File file = new File("IconPane.java");
            BufferedReader br = new BufferedReader(
                                new InputStreamReader(
                                new FileInputStream(file)));
            textPane.read(br, file);
            br.close();
            // Make up a couple of styles.
            int pos1 = 875, pos2 = 876;
            StyledDocument doc = textPane.getStyledDocument();
            Style style = textPane.addStyle("icon1", null);
            StyleConstants.setIcon(style, new ImageIcon(images[0]));
            // Set  icons.
            doc.setCharacterAttributes(pos1, 1, style, false);
            style = textPane.addStyle("icon2", null);
            StyleConstants.setIcon(style, new ImageIcon(images[1]));
            doc.setCharacterAttributes(pos2, 1, style, false);
            // Add the icons again with the insertString method.
            addContent(doc);
            // Show me.
            JScrollPane scrollPane = new JScrollPane(textPane);
            scrollPane.setPreferredSize(new Dimension(500,400));
            textPane.addMouseMotionListener(mouseInput);
            JOptionPane.showMessageDialog(null, scrollPane, "",
                                          JOptionPane.PLAIN_MESSAGE);
        private void addContent(StyledDocument doc) {
            int pos1 = 1667, pos2 = 1669;
            try {
                // Try inserting icons with insertString.
                doc.insertString(pos1, " ", doc.getStyle("icon1"));
                doc.insertString(pos2, " ", doc.getStyle("icon2"));
            } catch(BadLocationException e) {
                System.out.printf("bad location error: %s%n", e.getMessage());
        public static void main(String[] args) throws IOException {
            String[] ids = { "--g--", "---h-" };
            BufferedImage[] images = new BufferedImage[ids.length];
            for(int j = 0; j < images.length; j++)
                images[j] = ImageIO.read(new File("images/geek" + ids[j] + ".gif"));
            new IconPane().showTest(images);
        private MouseMotionAdapter mouseInput = new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                int pos = ((JTextComponent)e.getSource()).viewToModel(e.getPoint());
                System.out.println(String.valueOf(pos));
    }

  • How to save  JTextPane contents to a file ?

    Hello,
    I'd like to save the content of a JTextPane document into a buffer then to save it into a Database Column (I'm using MYSQL).
    If I'm using the getText() method, all attributes (color, font, and so forth) are lost
    I have also tried to use the write(Writer) method into a ByteOutputStream, but here again, attributes are lost.
    Thanks to anyone who may provide me with an example.
    Gege

    While the RTFEditorKit allows you to save files all with the same styling, the HTMLDocument class (if set as your JTextPane's StyledDocument) and HTMLEditorKit (works for both default StyledDocuments (on a more limited basis, I believe) and HTMLDocument's) allow you to save heterogeneous styling. However, it does NOT support the StyleConstants.ComponentAttribute, and does not provide a satisfactory exception when you attempt to use them (at least last time I checked - attempting to insert a component into an HTMLDocument yielded a NullPointerException, which wasn't useful at the time, but now that Java's gone open source or whatever, it's much more useful...).
    So anyway, the point is, you can probably just use your regular old JTextPane combined with HTMLEditorKit.write() and HTMLEditorKit.read() methods. You will need to translate components into some sort of text (if they're Serializable, just write them to a ByteArrayOutputStream and convert it into a String, add some custom escape-char-like magic, and you're there) before using the write method (and of course, translating it back after you read it in).
    Hope this helps.

  • Icon in a JTextPane

    hi, i'm trying to add an ImageIcon to a JTextPane, currently the JTextPane displays the contents of a DefaultStyledDocument. Whenever i try to add an Icon at the moment, i get a beep and nothing appears.
    I'm guessing that the DefaultStyledDocument can't display Icons, and if this is the case I'll have to either extend DefaultStyledDocument and add a method to display Icons, or implement AbstractDocument and then add Icon support. Trouble is, I have no idea where to start with either of these!
    Currently i construct the JTextPane like this:
    DefaultStyledDocument dsdtemp = new DefaultStyledDocument();
    JTextPane textPane = new JTextPane(dsdtemp);
    And i'm trying to add the icon like this:
    textPane.insertIcon(smileIcon);
    i've also tried:
    textPane.insertComponent(smileLabel);
    where smileLabel is just a JLabel containing the Icon i want.
    Can anyone help??
    thanks in advance

    hi again, after searching for hours on the topic, i found an answer 5 minutes after i posted here!
    it seems before you add the Icon you have to do:
    textPane.setEditable(true);
    and then set it false again after youve added what you want.
    Strange, but it works!

  • Caret position in HTML JTextPane

    Hi all,
    This question has been asked before, but with no satisfying answer that I can find so, in the hope that the eyes of a Swing text expert will fall upon this post, I'm having to ask again...
    Is there a simple means of translating the current caret position within a JTextPane to the offset within the HTML code it represents?
    In other words, where the JTextPane displays:Now is the time...The underlying HTML might be:<html><head></head><body><p align="left">Now is the time...</p></body></html>With the cursor positioned just in front of 'is', the caret position would be 4, but in the underlying HTML, the position would be 46.
    Any ideas, hints, suggestions or complete answers appreciated!
    Chris.

    I would suggest a trick.
    Suppose you ave actul caret position in JEditorPane.
    int caretPos=...;
    use HTLEditorKit.write(someWriter,htmlDoc,0,caretPos);
    Then you'll have a string
    <html><head></head><body><p align="left">Now </p></body></html>
    Then throw away all the closing tags and you'll have what you need by string length.
    Of course you would have to write kind of converter to clear out all formatting chars.
    regards,
    Stas

Maybe you are looking for

  • Thinkpad Twist- Hard Drive issues

    Hello all! I have a ThinkPad Twist that is still under warranty. A couple of weeks ago I got a 2100 HDD detection error . I am currently based in a rural part of Mexico for work (for a few months) and called into the US service center and they said I

  • JTable in JPanel in JTabbedPane in JScrollPane in JSplitPane problem

    I have a JSplitPane with a divider in the center; of which the top is a JPanel and the bottom is a JScrollPane that contains a JTabbedPane, for which each tab contains a JPanel which contains a JTable. When I move the divider up, so that it now takes

  • How do I convert mp3 to AIFF?

    The mp3 files plays poorly in FCE 4. I'm in iLife '09. On earlier versions of Garage Band and/or itunes, converting an mp3 to AIFF was pretty simple. Can anybody tell me what I need to do? Thanks, Terry D

  • It wont sync!

    OK, i keep trying to plug in my ipod and i want to press the "sync ipod" option under file but it will not let me click it. It isn't highlighted. Some please help, this is driving me insane. Does anyone know what this is, or how to fix it? Danielle

  • Need Info about FileUpload

    Hi Experts, Iam new to  WD ABAP. Iam uploading one file from my local system using FileUpload. i need to do following things. 1: I should get Only name and type  of file ( when getting from context that is binded, It's giving full path of file ).. 2: