Layout of a JTextPane

I have a app where i drag jpg files from a JFileChooser to a JTextPane. The JTextpane displays what was dragged as pictures if it is a jpg file. i allow for multiple pictues to be displayed and i allow for removal of a picture by setting it visible to false. the problem that i have is that when i call revalidate on the JTextpane the rest of the pictures do not move fill in the gaps left when pictues are removed. ie
pic pic pic space
pic pic pic pic
validate does not create
pic pic pic pic
pic pic pic
Could anyone help me to resolve my problem
Thanks

I was afraid of that but i could not find any method on the api that would suggest the total destruction of the object placed in the JTextPane.
Anyone with a suggestion to totaly destroy the the image. PS the Image is a a class that extends JComponent.
Thanks

Similar Messages

  • HELP ----About JTextPane

    How many characters can JTextPane contain in a line?
    I want input 10000 letters in a line , but it can't run correctly.
    Why? How to account for it?
    I test it in this code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TestNoWrap extends JFrame
    JTextPane textPane;
    JScrollPane scrollPane;
    public TestNoWrap()
    JPanel panel = new JPanel();
    panel.setLayout( new BorderLayout() );
    setContentPane( panel );
    // no wrap by adding text pane to a panel using border layout
    textPane = new JTextPane();
    textPane.setText("1234567890 1234567890 1234567890");
    JPanel noWrapPanel = new JPanel();
    noWrapPanel.setLayout( new BorderLayout() );
    noWrapPanel.add( textPane );
    scrollPane = new JScrollPane( noWrapPanel );
    scrollPane.setPreferredSize( new Dimension( 200, 100 ) );
    panel.add( scrollPane, BorderLayout.NORTH );
    // no wrap by overriding text pane methods
    textPane = new JTextPane()
    public void setSize(Dimension d)
    if (d.width < getParent().getSize().width)
    d.width = getParent().getSize().width;
    super.setSize(d);
    public boolean getScrollableTracksViewportWidth()
    return false;
    for (int i=0;i<10000;i++)
    textPane.setText("1234567890 1234567890 1234567890");
    scrollPane = new JScrollPane( textPane );
    scrollPane.setPreferredSize( new Dimension( 200, 100 ) );
    panel.add( scrollPane );
    public static void main(String[] args)
    TestNoWrap frame = new TestNoWrap();
    frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
    frame.pack();
    frame.setVisible(true);
    }

    Hello,
    When you call setText() method, you can do this:
    yourJTextPane.setCaretPosition(yourJTextPane.getDocument().getLength());

  • JTextPane - horizontal scrolling

    hey all,
    this is, I'm sure, a stupid question... but it has me stumped.
    I've got an exception dialog for handling uncaught exceptions - and I want to display the stack trace there. I'm using a JTextPane for this, but my problem is that it doesn't seem to be capable ot horizontal scrolling (or rather I cant make it work!).
    I have the scrollbars on - but thats on the scroll pane, and I think there's probably something I need to do to the text pane to make this work....
    simple answer someone?
    ta
    dim

    Here is a program the shows two ways of having the horizontal scrollBar appear when required:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TestNoWrap extends JFrame
         JTextPane textPane;
         JScrollPane scrollPane;
         public TestNoWrap()
              JPanel panel = new JPanel();
              panel.setLayout( new BorderLayout() );
              setContentPane( panel );
              // no wrap by adding text pane to a panel using border layout
              textPane = new JTextPane();
              textPane.setText("1234567890 1234567890 1234567890");
              JPanel noWrapPanel = new JPanel();
              noWrapPanel.setLayout( new BorderLayout() );
              noWrapPanel.add( textPane );
              scrollPane = new JScrollPane( noWrapPanel );
              scrollPane.setPreferredSize( new Dimension( 200, 100 ) );
              panel.add( scrollPane, BorderLayout.NORTH );
              // no wrap by overriding text pane methods
              textPane = new JTextPane()
                   public void setSize(Dimension d)
                        if (d.width < getParent().getSize().width)
                             d.width = getParent().getSize().width;
                        super.setSize(d);
                   public boolean getScrollableTracksViewportWidth()
                        return false;
              textPane.setText("1234567890 1234567890 1234567890");
              scrollPane = new JScrollPane( textPane );
              scrollPane.setPreferredSize( new Dimension( 200, 100 ) );
              panel.add( scrollPane );
         public static void main(String[] args)
              TestNoWrap frame = new TestNoWrap();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • JTextPane/JScrollPane problems

    in my JTextPane i would like to be able to set the tab size (like you can with JTextArea), and for some reason my JScrollPane doesn't want to scroll the JTextPane horizontally, it just wraps the text. any help and sample code is very appreciated.
    TravenE

    Well normally I'd tell you to search the forums because I've answered both of these question several times before. But since the search isn't currently working for me I'm assuming it isn't working for you either, so here are my suggestons.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TextPaneTabs extends JFrame
         public TextPaneTabs()
              JTextPane textPane = new JTextPane();
              textPane.setFont( new Font("monospaced", Font.PLAIN, 12) );
              JScrollPane scrollPane = new JScrollPane( textPane );
              scrollPane.setPreferredSize( new Dimension( 200, 200 ) );
              getContentPane().add( scrollPane );
              setTabs( textPane, 4 );
         public void setTabs( JTextPane textPane, int charactersPerTab)
              FontMetrics fm = textPane.getFontMetrics( textPane.getFont() );
              int charWidth = fm.charWidth( 'w' );
              int tabWidth = charWidth * charactersPerTab;
              TabStop[] tabs = new TabStop[10];
              for (int j = 0; j < tabs.length; j++)
                   int tab = j + 1;
                   tabs[j] = new TabStop( tab * tabWidth );
              TabSet tabSet = new TabSet(tabs);
              SimpleAttributeSet attributes = new SimpleAttributeSet();
              StyleConstants.setTabSet(attributes, tabSet);
              int length = textPane.getDocument().getLength();
              textPane.getStyledDocument().setParagraphAttributes(0, length, attributes, false);
         public static void main(String[] args)
              TextPaneTabs frame = new TextPaneTabs();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TestNoWrap extends JFrame
         JTextPane textPane;
         JScrollPane scrollPane;
         public TestNoWrap()
              JPanel panel = new JPanel();
              panel.setLayout( new BorderLayout() );
              setContentPane( panel );
              // no wrap by adding text pane to a panel using border layout
              textPane = new JTextPane();
              textPane.setText("1234567890 1234567890 1234567890");
              JPanel noWrapPanel = new JPanel();
              noWrapPanel.setLayout( new BorderLayout() );
              noWrapPanel.add( textPane );
              scrollPane = new JScrollPane( noWrapPanel );
              scrollPane.setPreferredSize( new Dimension( 200, 100 ) );
              panel.add( scrollPane, BorderLayout.NORTH );
              // no wrap by overriding text pane methods
              textPane = new JTextPane()
                   public void setSize(Dimension d)
                        if (d.width < getParent().getSize().width)
                             d.width = getParent().getSize().width;
                        super.setSize(d);
                   public boolean getScrollableTracksViewportWidth()
                        return false;
              textPane.setText("1234567890 1234567890 1234567890");
              scrollPane = new JScrollPane( textPane );
              scrollPane.setPreferredSize( new Dimension( 200, 100 ) );
              panel.add( scrollPane );
         public static void main(String[] args)
              TestNoWrap frame = new TestNoWrap();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • Line Number in JTextPane

    Hi Experts;
    How do I add a caret listener on this code so that it will just add a number
    when the user goes to the next line.
    import java.awt.*;
    import javax.swing.*;
    public class LineNumber extends JComponent
         private final static Color DEFAULT_BACKGROUND = new Color(213, 213, 234);
         private final static Color DEFAULT_FOREGROUND = Color.white;
         private final static Font DEFAULT_FONT = new Font("arial", Font.PLAIN, 11);
         // LineNumber height (abends when I use MAX_VALUE)
         private final static int HEIGHT = Integer.MAX_VALUE - 1000000;
         // Set right/left margin
         private final static int MARGIN = 5;
         // Line height of this LineNumber component
         private int lineHeight;
         // Line height of this LineNumber component
         private int fontLineHeight;
         // With of the LineNumber component
         private int currentRowWidth;
         // Metrics of this LineNumber component
         private FontMetrics fontMetrics;
          * Convenience constructor for Text Components
         public LineNumber(JComponent component)
              if (component == null)
                   setBackground( DEFAULT_BACKGROUND );
                   setForeground( DEFAULT_FOREGROUND );
                   setFont( DEFAULT_FONT );
              else
                   setBackground( DEFAULT_BACKGROUND );
                   setForeground( DEFAULT_FOREGROUND );
                   setFont( component.getFont() );
              setPreferredSize( 99 );
         public void setPreferredSize(int row)
              int width = fontMetrics.stringWidth( String.valueOf(row) );
              if (currentRowWidth < width)
                   currentRowWidth = width;
                   setPreferredSize( new Dimension(2 * MARGIN + width, HEIGHT) );
         public void setFont(Font font)
              super.setFont(font);
              fontMetrics = getFontMetrics( getFont() );
              fontLineHeight = fontMetrics.getHeight();
          * The line height defaults to the line height of the font for this
          * component. The line height can be overridden by setting it to a
          * positive non-zero value.
         public int getLineHeight()
              if (lineHeight == 0)
                   return fontLineHeight;
              else
                   return lineHeight;
         public void setLineHeight(int lineHeight)
              if (lineHeight > 0)
                   this.lineHeight = lineHeight;
         public int getStartOffset()
              return 4;
         public void paintComponent(Graphics g)
               int lineHeight = getLineHeight();
               int startOffset = getStartOffset();
               Rectangle drawHere = g.getClipBounds();
               g.setColor( getBackground() );
               g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height);
               g.setColor( getForeground() );
               int startLineNumber = (drawHere.y / lineHeight) + 1;
               int endLineNumber = startLineNumber + (drawHere.height / lineHeight);
               int start = (drawHere.y / lineHeight) * lineHeight + lineHeight - startOffset;
               for (int i = startLineNumber; i <= endLineNumber; i++)
               String lineNumber = String.valueOf(i);
               int width = fontMetrics.stringWidth( lineNumber );
               g.drawString(lineNumber, MARGIN + currentRowWidth - width, start);
               start += lineHeight;
               setPreferredSize( endLineNumber );
    } Thanks for your time . . .
    The_Developer

    Here's what I use. It behaves correctly WRT wrapped lines, and should work equally well with a JTextArea or a JTextPane.
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Rectangle;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.BorderFactory;
    import javax.swing.JComponent;
    import javax.swing.SizeSequence;
    import javax.swing.UIManager;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.Element;
    import javax.swing.text.JTextComponent;
    * LineNumberView is a simple line-number gutter that works correctly
    * even when lines are wrapped in the associated text component.  This
    * is meant to be used as the RowHeaderView in a JScrollPane that
    * contains the associated text component.  Example usage:
    *<pre>
    *   JTextArea ta = new JTextArea();
    *   ta.setLineWrap(true);
    *   ta.setWrapStyleWord(true);
    *   JScrollPane sp = new JScrollPane(ta);
    *   sp.setRowHeaderView(new LineNumberView(ta));
    *</pre>
    * @author Alan Moore
    public class LineNumberView extends JComponent
      // This is for the border to the right of the line numbers.
      // There's probably a UIDefaults value that could be used for this.
      private static final Color BORDER_COLOR = Color.GRAY;
      private static final int WIDTH_TEMPLATE = 99999;
      private static final int MARGIN = 5;
      private FontMetrics viewFontMetrics;
      private int maxNumberWidth;
      private int componentWidth;
      private int textTopInset;
      private int textFontAscent;
      private int textFontHeight;
      private JTextComponent text;
      private SizeSequence sizes;
      private int startLine = 0;
      private boolean structureChanged = true;
       * Construct a LineNumberView and attach it to the given text component.
       * The LineNumberView will listen for certain kinds of events from the
       * text component and update itself accordingly.
       * @param startLine the line that changed, if there's only one
       * @param structureChanged if <tt>true</tt>, ignore the line number and
       *     update all the line heights.
      public LineNumberView(JTextComponent text)
        if (text == null)
          throw new IllegalArgumentException("Text component cannot be null");
        this.text = text;
        updateCachedMetrics();
        UpdateHandler handler = new UpdateHandler();
        text.getDocument().addDocumentListener(handler);
        text.addPropertyChangeListener(handler);
        text.addComponentListener(handler);
        setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, BORDER_COLOR));
       * Schedule a repaint because one or more line heights may have changed.
       * @param startLine the line that changed, if there's only one
       * @param structureChanged if <tt>true</tt>, ignore the line number and
       *     update all the line heights.
      private void viewChanged(int startLine, boolean structureChanged)
        this.startLine = startLine;
        this.structureChanged = structureChanged;
        revalidate();
        repaint();
      /** Update the line heights as needed. */
      private void updateSizes()
        if (startLine < 0)
          return;
        if (structureChanged)
          int count = getAdjustedLineCount();
          sizes = new SizeSequence(count);
          for (int i = 0; i < count; i++)
            sizes.setSize(i, getLineHeight(i));
          structureChanged = false;
        else
          sizes.setSize(startLine, getLineHeight(startLine));
        startLine = -1;
      /* Copied from javax.swing.text.PlainDocument */
      private int getAdjustedLineCount()
        // There is an implicit break being modeled at the end of the
        // document to deal with boundary conditions at the end.  This
        // is not desired in the line count, so we detect it and remove
        // its effect if throwing off the count.
        Element map = text.getDocument().getDefaultRootElement();
        int n = map.getElementCount();
        Element lastLine = map.getElement(n - 1);
        if ((lastLine.getEndOffset() - lastLine.getStartOffset()) > 1)
          return n;
        return n - 1;
       * Get the height of a line from the JTextComponent.
       * @param index the line number
       * @param the height, in pixels
      private int getLineHeight(int index)
        int lastPos = sizes.getPosition(index) + textTopInset;
        int height = textFontHeight;
        try
          Element map = text.getDocument().getDefaultRootElement();
          int lastChar = map.getElement(index).getEndOffset() - 1;
          Rectangle r = text.modelToView(lastChar);
          height = (r.y - lastPos) + r.height;
        catch (BadLocationException ex)
          ex.printStackTrace();
        return height;
       * Cache some values that are used a lot in painting or size
       * calculations. Also ensures that the line-number font is not
       * larger than the text component's font (by point-size, anyway).
      private void updateCachedMetrics()
        Font textFont = text.getFont();
        FontMetrics fm = getFontMetrics(textFont);
        textFontHeight = fm.getHeight();
        textFontAscent = fm.getAscent();
        textTopInset = text.getInsets().top;
        Font viewFont = getFont();
        boolean changed = false;
        if (viewFont == null)
          viewFont = UIManager.getFont("Label.font");
          changed = true;
        if (viewFont.getSize() > textFont.getSize())
          viewFont = viewFont.deriveFont(textFont.getSize2D());
          changed = true;
        viewFontMetrics = getFontMetrics(viewFont);
        maxNumberWidth = viewFontMetrics.stringWidth(String.valueOf(WIDTH_TEMPLATE));
        componentWidth = 2 * MARGIN + maxNumberWidth;
        if (changed)
          super.setFont(viewFont);
      public Dimension getPreferredSize()
        return new Dimension(componentWidth, text.getHeight());
      public void setFont(Font font)
        super.setFont(font);
        updateCachedMetrics();
      public void paintComponent(Graphics g)
        updateSizes();
        Rectangle clip = g.getClipBounds();
        g.setColor(getBackground());
        g.fillRect(clip.x, clip.y, clip.width, clip.height);
        g.setColor(getForeground());
        int base = clip.y - textTopInset;
        int first = sizes.getIndex(base);
        int last = sizes.getIndex(base + clip.height);
        String text = "";
        for (int i = first; i <= last; i++)
          text = String.valueOf(i+1);
          int x = MARGIN + maxNumberWidth - viewFontMetrics.stringWidth(text);
          int y = sizes.getPosition(i) + textFontAscent + textTopInset;
          g.drawString(text, x, y);
      class UpdateHandler extends ComponentAdapter
          implements PropertyChangeListener, DocumentListener
         * The text component was resized. 'Nuff said.
        public void componentResized(ComponentEvent evt)
          viewChanged(0, true);
         * A bound property was changed on the text component. Properties
         * like the font, border, and tab size affect the layout of the
         * whole document, so we invalidate all the line heights here.
        public void propertyChange(PropertyChangeEvent evt)
          Object oldValue = evt.getOldValue();
          Object newValue = evt.getNewValue();
          String propertyName = evt.getPropertyName();
          if ("document".equals(propertyName))
            if (oldValue != null && oldValue instanceof Document)
              ((Document)oldValue).removeDocumentListener(this);
            if (newValue != null && newValue instanceof Document)
              ((Document)newValue).addDocumentListener(this);
          updateCachedMetrics();
          viewChanged(0, true);
         * Text was inserted into the document.
        public void insertUpdate(DocumentEvent evt)
          update(evt);
         * Text was removed from the document.
        public void removeUpdate(DocumentEvent evt)
          update(evt);
         * Text attributes were changed.  In a source-code editor based on
         * StyledDocument, attribute changes should be applied automatically
         * in response to inserts and removals.  Since we're already
         * listening for those, this method should be redundant, but YMMV.
        public void changedUpdate(DocumentEvent evt)
    //      update(evt);
         * If the edit was confined to a single line, invalidate that
         * line's height.  Otherwise, invalidate them all.
        private void update(DocumentEvent evt)
          Element map = text.getDocument().getDefaultRootElement();
          int line = map.getElementIndex(evt.getOffset());
          DocumentEvent.ElementChange ec = evt.getChange(map);
          viewChanged(line, ec != null);
    }

  • Bug in JTextArea/JTextPane ??

    Hi,
    I am facing huge memory leak problems with JTextArea/JTextPane. After considerable investigation, I found out that the Document associated with the component is not being GC'ed properly. I ran OptimizeIt and found out that the memory is being consumed by the JTextPane.setText() method. I have implmented a HTML viewer to display large amounts of HTML data and it is leaking memory like crazy on each successive execution. Any thoughts ??
    JDK1.4.2_01, WinXP
    Here is the code fragment:
    public class ReportViewer extends BaseFrame implements FontChange_int
         private     String          cReport;          
         private boolean          testMode = false;     
         // Graphical components
         private     BorderLayout     cMainLayout;
         private     JButton          cClose;
         private     JTextPane     cRptPane;
         private     Button          cClose2;
         private ViewUpdater cViewUpdater = null;
         // Constants
         final     static     int     startupXSize = 650;
         final     static     int     startupYSize = 500;
         // Methods
         public ReportViewer(String report, ReportMain main)
              // BaseFrame extends JFrame
              super("Reports Viewer", true, startupXSize, startupYSize);
              testMode = false;
              cReport = report;
              cViewUpdater = new ViewUpdater();
              initialize();
         public void initialize()
              // Create main layout manager
              cMainLayout = new BorderLayout();
              getContentPane().setLayout(cMainLayout);
              // Quick button bar - print, export, save as
              JToolBar     topPanel = new JToolBar();
              topPanel.setBorder(new BevelBorder(BevelBorder.RAISED) );
              java.net.URL     url;
              topPanel.add(Box.createHorizontalStrut(10));
              url = Scm.class.getResource("images/Exit.gif");
              cClose = new Button(new ImageIcon(url), true);
              cClose.setToolTipText("Close Window");
              topPanel.add(cClose);
              getContentPane().add(topPanel, BorderLayout.NORTH);
              // Main view window - HTML
              cRptPane = new JTextPane();
              cRptPane.setContentType("text/html");
              cRptPane.setEditable(false);
              JScrollPane sp = new JScrollPane(cRptPane);
              getContentPane().add(sp, BorderLayout.CENTER);
              // Main button - Close
              JPanel     bottomPanel = new JPanel();
              url = Scm.class.getResource("images/Exit.gif");
              cClose2 = new Button(new ImageIcon(url), "Close");
              bottomPanel.add(cClose2);
              getContentPane().add(bottomPanel, BorderLayout.SOUTH);
              cClose.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              cClose2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              show();
              cViewUpdater.setText(cReport);
              SwingUtilities.invokeLater(cViewUpdater);
         protected void
         closeWindow()
              super.closeWindow();
              // If I add the following lines, the GC reclaims
    // part of the memory but does not flush out the text
    // component as a whole
              /*Document doc = cRptPane.getDocument();
              try
                   doc.remove(0,doc.getLength());
              catch(Exception e) {;}
              doc=null; */
              cRptPane=null;
              cReport = null;
              cViewUpdater = null;
              dispose();
         private class ViewUpdater implements Runnable
              private String cText = null;
              public ViewUpdater() {;}
              public void
              setText(String text) {
                   cText = text;
              public void
              run() {
                   cRptPane.setText(cText);
                   cRptPane.setCaretPosition(0);
                   cText = null;
         // Local main - for testing
         public static void main(String args[])
              //new ReportViewer(str,comp);
    Sudarshan
    www.spectrumscm.com

    Hi,
    I am facing huge memory leak problems with JTextArea/JTextPane. After considerable investigation, I found out that the Document associated with the component is not being GC'ed properly. I ran OptimizeIt and found out that the memory is being consumed by the JTextPane.setText() method. I have implmented a HTML viewer to display large amounts of HTML data and it is leaking memory like crazy on each successive execution. Any thoughts ??
    JDK1.4.2_01, WinXP
    Here is the code fragment:
    public class ReportViewer extends BaseFrame implements FontChange_int
         private     String          cReport;          
         private boolean          testMode = false;     
         // Graphical components
         private     BorderLayout     cMainLayout;
         private     JButton          cClose;
         private     JTextPane     cRptPane;
         private     Button          cClose2;
         private ViewUpdater cViewUpdater = null;
         // Constants
         final     static     int     startupXSize = 650;
         final     static     int     startupYSize = 500;
         // Methods
         public ReportViewer(String report, ReportMain main)
              // BaseFrame extends JFrame
              super("Reports Viewer", true, startupXSize, startupYSize);
              testMode = false;
              cReport = report;
              cViewUpdater = new ViewUpdater();
              initialize();
         public void initialize()
              // Create main layout manager
              cMainLayout = new BorderLayout();
              getContentPane().setLayout(cMainLayout);
              // Quick button bar - print, export, save as
              JToolBar     topPanel = new JToolBar();
              topPanel.setBorder(new BevelBorder(BevelBorder.RAISED) );
              java.net.URL     url;
              topPanel.add(Box.createHorizontalStrut(10));
              url = Scm.class.getResource("images/Exit.gif");
              cClose = new Button(new ImageIcon(url), true);
              cClose.setToolTipText("Close Window");
              topPanel.add(cClose);
              getContentPane().add(topPanel, BorderLayout.NORTH);
              // Main view window - HTML
              cRptPane = new JTextPane();
              cRptPane.setContentType("text/html");
              cRptPane.setEditable(false);
              JScrollPane sp = new JScrollPane(cRptPane);
              getContentPane().add(sp, BorderLayout.CENTER);
              // Main button - Close
              JPanel     bottomPanel = new JPanel();
              url = Scm.class.getResource("images/Exit.gif");
              cClose2 = new Button(new ImageIcon(url), "Close");
              bottomPanel.add(cClose2);
              getContentPane().add(bottomPanel, BorderLayout.SOUTH);
              cClose.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              cClose2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              show();
              cViewUpdater.setText(cReport);
              SwingUtilities.invokeLater(cViewUpdater);
         protected void
         closeWindow()
              super.closeWindow();
              // If I add the following lines, the GC reclaims
    // part of the memory but does not flush out the text
    // component as a whole
              /*Document doc = cRptPane.getDocument();
              try
                   doc.remove(0,doc.getLength());
              catch(Exception e) {;}
              doc=null; */
              cRptPane=null;
              cReport = null;
              cViewUpdater = null;
              dispose();
         private class ViewUpdater implements Runnable
              private String cText = null;
              public ViewUpdater() {;}
              public void
              setText(String text) {
                   cText = text;
              public void
              run() {
                   cRptPane.setText(cText);
                   cRptPane.setCaretPosition(0);
                   cText = null;
         // Local main - for testing
         public static void main(String args[])
              //new ReportViewer(str,comp);
    Sudarshan
    www.spectrumscm.com

  • How can I change the layout on this JDialog?

    Hi , I have the following Dialog with some content. As of now, the line after the separator is displayed in two lines. I was looking for a way to show that in one line and change the column widths a bit so that the rest of the content can each be shown on one line as well, according to the look and feel of a table.
    Here's the code:Please download [TableLayout.jar|http://java.sun.com/products/jfc/tsc/articles/tablelayout/apps/TableLayout.jar] in order to compile.
    Thanks!
    import layout.TableLayout;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JSeparator;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextPane;
    import javax.swing.text.StyledEditorKit;
    public class MyDialogTest implements layout.TableLayoutConstants {
         JTabbedPane pane;
         JDialog myDialog;
         JTextPane infoPanel;
        public MyDialogTest() {
             myDialog = new JDialog();
             myDialog.setTitle("MyDialogTest");
             pane = new JTabbedPane();
             JPanel panel = new JPanel(new BorderLayout());
             panel.add(makeTab(), BorderLayout.CENTER);
             pane.addTab("About", panel);
             myDialog.getContentPane().add(pane);
             myDialog.setSize(500, 620);
             myDialog.setResizable(false);
             myDialog.setVisible(true);
        private Component makeTab() {
             JPanel aboutPanel = new JPanel();
            double [][] size = {{PREFERRED, FILL},{PREFERRED, PREFERRED, PREFERRED, PREFERRED, PREFERRED, PREFERRED, PREFERRED, PREFERRED, PREFERRED, PREFERRED, FILL}};
            TableLayout layout = new TableLayout(size);
            aboutPanel.setLayout(layout);
            JLabel headerLabel = new JLabel("About This Application");
            aboutPanel.add(headerLabel, "0, 0, 1, 0");
            aboutPanel.add(new JLabel("Version 4.1"), "0, 1, 1, 1");
            aboutPanel.add(new JLabel(" "), "0, 2, 1, 2");
            aboutPanel.add(new JLabel("Customer Service: 1-800-888-8888"), "0, 3, 1, 3");
            JLabel yahooUrl = new JLabel("www.yahoo.com");
            aboutPanel.add(yahooUrl, "0, 4");
            aboutPanel.add(new JLabel(" "), "0, 5");
            aboutPanel.add(new JSeparator(), "0, 6, 1, 6");
            aboutPanel.add(new JLabel(" "), "0, 7");
            infoPanel = new JTextPane();
            infoPanel.setEditable(false);
            infoPanel.setEditorKit(new StyledEditorKit());
            infoPanel.setContentType("text/html");
            makeInfoPanel();
            aboutPanel.add(infoPanel, "0, 8, 1, 8");
            JButton copyToClipboardButton = new JButton("Button1");
            JButton moreInformationButton = new JButton("Button2");
            JPanel buttonPanel = new JPanel();
            buttonPanel.add(copyToClipboardButton);
            buttonPanel.add(moreInformationButton);
            aboutPanel.add(buttonPanel, "0, 9");
            return aboutPanel;
        private void makeInfoPanel() {
              StringBuffer infoPaneContent = new StringBuffer("<html><head></head><body><table>");
              infoPaneContent.append("<tr><td>Version 4.1 (build  111708-063624"+ "</td></tr>");
              infoPaneContent.append("<tr><td>Customer IP Address:</td>&nbsp <td>10.53.62.11</td></tr>");
              infoPaneContent.append("<tr><td>JMS Server:</td>&nbsp <td>myserver</td></tr>");
              infoPaneContent.append("<tr><td>Quote Server:</td>&nbsp <td>qs2w62m3/qs106w60m3</td></tr>");
              infoPaneContent.append("<tr><td>Login ID:</td>&nbsp <td>programmer girl</td></tr>");
              infoPaneContent.append("<tr><td>Java Version:</td> &nbsp<td>"+ System.getProperty("java.version") + "</td></tr>");
              infoPaneContent.append("<tr><td>Operating System:</td> &nbsp<td>"+ System.getProperty("os.name") + " "+ System.getProperty("os.version") + " ("+ ")" + "</td></tr>");
             infoPaneContent.append("<tr><td>Browser Version:</td>&nbsp <td>"+ "Mozilla/4.0(compatible: MSIE 6.0; Windows NT 5.1; SV!; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648" + "</td></tr>");
              Runtime rt = Runtime.getRuntime();
              infoPaneContent.append("<tr><td>Free Memory (KB):</td>&nbsp <td>("+ rt.freeMemory() / 1000 + " / " + rt.totalMemory() / 1000+ ")</td></tr>");
              infoPaneContent.append("<tr><td>Symbols In Use:</td>&nbsp<td>symbol</td></tr>");
              infoPaneContent.append("<tr><td>JMS :</td>&nbsp<td>connected</td></tr>");
              infoPaneContent.append("<tr><td>Market Data :</td>&nbsp<td>connected</td></tr>");
              infoPaneContent.append("<tr></tr>");
              infoPaneContent.append("<tr></tr>");
              infoPaneContent.append("</table></body></html>");
              infoPanel.setText(infoPaneContent.toString());
         public static void main(String[] args) {
              MyDialogTest test = new MyDialogTest();
    }

    Just sign out and sign in with your UK Apple ID
    Edit: If you press your name on this page (top left), you get "Actions" on the right side. Here you can change timezone, location etc.

  • Exception while adding a chrtpanel(component of JFreeChart) to JTextPane.

    hi,
    Please help for solving the following exception while adding a chrtpanel(component of JFreeChart) to JTextPane
    java.lang.ArrayIndexOutOfBoundsException: No such child: 0
         at java.awt.Container.getComponent(Container.java:237)
         at javax.swing.text.ComponentView$Invalidator.cacheChildSizes(ComponentView.jav
    a:399)
         at javax.swing.text.ComponentView$Invalidator.doLayout(ComponentView.java:383)
         at java.awt.Container.validateTree(Container.java:1092)
         at java.awt.Container.validate(Container.java:1067)
         at javax.swing.text.ComponentView$Invalidator.validateIfNecessary(ComponentView
    .java:394)
         at javax.swing.text.ComponentView$Invalidator.getPreferredSize(ComponentView.ja
    va:427)
         at javax.swing.text.ComponentView.getPreferredSpan(ComponentView.java:119)
         at javax.swing.text.FlowView$LogicalView.getPreferredSpan(FlowView.java:679)
         at javax.swing.text.FlowView.calculateMinorAxisRequirements(FlowView.java:214)
         at javax.swing.text.BoxView.checkRequests(BoxView.java:913)
         at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:542)
         at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:881)
         at javax.swing.text.BoxView.checkRequests(BoxView.java:913)
         at javax.swing.text.BoxView.setSpanOnAxis(BoxView.java:325)
         at javax.swing.text.BoxView.layout(BoxView.java:682)
         at javax.swing.text.BoxView.setSize(BoxView.java:379)
         at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(BasicTextUI.java:1599)
         at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(BasicTextUI.java:801)
         at javax.swing.JComponent.getPreferredSize(JComponent.java:1275)
         at javax.swing.JEditorPane.getPreferredSize(JEditorPane.java:1212)
         at javax.swing.ScrollPaneLayout.layoutContainer(ScrollPaneLayout.java:769)
         at java.awt.Container.layout(Container.java:1020)
         at java.awt.Container.doLayout(Container.java:1010)
         at java.awt.Container.validateTree(Container.java:1092)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validate(Container.java:1067)
         at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:353
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQu
    eueUtilities.java:116)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:454)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.ja
    va:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java
    :151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)

    I tried with the following link
    http://www.onjava.com/pub/a/onjava/2004/03/10/blackmamba.html?page=2
    one place this one is getting solved. Some other places atill the exeception is present.

  • Putting a panel using null layout in in a JScrollPane

    Hi,
    I'm trying to create a form for the screen which looks exactly like its equivalent on paper. The form has a grid of cells that can be typed into.
    My approach so far has been to use a JTextPane for each cell and use absolute positioning to put these onto a JPanel with a null layout.
    This has worked well so far, but the JPanel is taller than the screen so I want to put it inside a JScrollPane.
    However the scrollbars don't show up.
    Can someone point out what I need to implement to be able to scroll my null layout JPanel in a JScrollPane.
    Thanks.

    That was nice and simple. The Duke's are yours.
    One problem leads to another unfortunately.
    I want the form to be centered so I put it in another JPanel with BorderLayout then put that in the JScrollPane. Unfortunately it is not centred.
    JPanel nullLayoutPanel = new JPanel();
    nullLayoutPanel.setLayout(null);
    // layout components on panel
    JPanel panelToKeepFormCentered= new JPanel(new BorderLayout());
    panelToKeepFormCentered.add(nullLayoutPanel, BorderLayout.CENTER);
    JFrame frame = new JFrame();
    frame.getContentPane().add(new JScrollPane(panelToKeepFormCentered));Hope it is clear what I'm trying to achieve.
    When the JFrame is smaller than the form (the nullLayoutPanel), scrollbars should show (they do now thanks to Noah).
    When the JFrame is bigger than the form, the form's JPanel should be centred in the JFrame with blank space around.
    Thanks.

  • JScrollPane, JTextPane, Weird scrolling happening

    The code below shows the problem I am having: In short, I have a textPane in a scrollPane but when I try to getViewPort.setViewPosition(0,0); then the scroll pane briefly flashes to position 0,0 then re positions itself to display the bottom of the text pane. It is driving me wild! If I removed the InsertString function call used on the Document of the textPane, then it works as I thought it should (apart from an initial glitch where the slider bar is placed near the top...- see example)
    in the example I have a 'tall' JTextPane (ie, lot's of linefeeds) with a red panel all in a JPanel which inturn lies in a JScrollPane. Click on the 'Force Update' button to force the Text pane to be updated (in my real java class, there is other stuff to change the values of the textpane) and to set the display position to 0,0. Notice how the slider button flashes to the top of the vertical bar then returns to the bottom. If you cick on the 'toggle InsetString Active' button, then the code to Insert the String to the textArea is by-passed. Now clicking on the 'Force Update' button (after the initial glitch) does send the view to the top of the Jpanel(which now contains an empty textarea and a red panel).
    Can anyone give any clues as to what is causing the Scroll pane to redraw to the bottom of the panel? (and what is causing the glitch after the toggle InsertString button is pressed?)
    I have tried it on JDK 1.3.1 and 1.4 and scoured the groups for similar problems but found none. Lots have people had prblems getting the JScrollpane to the bottom of the textpane but I can't seem to stop it going down!
    I'd appreciate any help as I'm quickly going bald....
    Marc
    code begins....
    -------------------------cut here--------------------------
    import javax.swing.*;
    import java.awt.*; //for layout managers
    import java.awt.event.*; //for action and window events
    import javax.swing.text.*;
    public class WierdScroll extends JFrame
    ScrollPane scrollPane = null;
    JButton button = null;
    JButton b2 = null;
    JPanel screen = null;
    // below is the style to be associated with the textpane
    static private SimpleAttributeSet normalStyle = new SimpleAttributeSet(StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE));
    static
    StyleConstants.setFontFamily(normalStyle, "Courier");
    StyleConstants.setFontSize(normalStyle, 12);
    public WierdScroll()
    super("Wierd Scrolling \'feature\'");
    // create and setup the components
    screen = new JPanel();
    scrollPane = new ScrollPane();
    scrollPane.setVerticalScrollBarPolicy(
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setPreferredSize(new Dimension(250, 155));
    scrollPane.setMinimumSize(new Dimension(10, 10));
    scrollPane.updateConstraintView();
    button = new JButton("Force update");
    button.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent e)
    scrollPane.updateConstraintView();
    b2 = new JButton("toggle InsertString Active");
    b2.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent e)
    JButton b = (JButton) e.getSource();
    scrollPane.allowInsertString = !scrollPane.allowInsertString;
    scrollPane.updateConstraintView();
    // add the component to the frame
    screen.add(scrollPane);
    screen.add(button);
    screen.add(b2);
    getContentPane().add(screen);
    public static void main(String[] args) {
    JFrame frame = new WierdScroll();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.pack();
    frame.setVisible(true);
    // this extended class is the scrollpane. The problem occurrs when the doc.insertString function is called;
    // When insertString is called, the scroll pane flicks to the bottom of the scroll view but when insertString
    // is not called then the setViewPostion works OK....
    public class ScrollPane extends JScrollPane
    public JPanel panel;
    public JTextPane margin;
    public boolean allowInsertString = true;
    /** Creates a new instance of ConstraintView */
    public ScrollPane()
    // create the pane
    margin = new JTextPane();
    // create the label
    JPanel jp = new JPanel();
    jp.setBackground(Color.red);
    jp.setPreferredSize(new Dimension(500,500));
    panel = new JPanel();
    panel.setBackground(Color.white);
    // add the label and pane to the panel
    panel.add(margin);
    panel.add(jp);
    // set the scroll voew to be the panel
    setViewportView(panel);
    public void updateConstraintView()
    // if doc has stuff in it, then clear contents
    Document doc = margin.getDocument();
    if (doc.getLength() > 0)
    try
    doc.remove(0, doc.getLength());
    catch (BadLocationException ble) {}
    // the allowInsertString is toggled via button on screen to stop insertString call
    if (allowInsertString)
    try {
    doc.insertString(0, "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n", normalStyle);
    catch (BadLocationException ble) {}
    // set viewport so that it scrolls to top
    getViewport().setViewPosition(new Point(0,0));

    Cheers!
    using the setCaretPosition() of the JTextPane instead of the getViewport().setViewPosition(new Point(0,0)) method of the JScrollPane works a treat.
    But I would have thought that the scroll pane should have 'complete' control (unless specified by programmer) of what it displays. It seems strange to have a component of a scrollpane dictate to the scrollpane what it should show...
    Thanks for your assistance.
    On a different note, has anyone noticed that the word 'c l a s s' has become cl***?? Is this a victim of sun's new swear filter to go with the new site look?

  • From jtextpane to jeditorpane

    I'd like to create a complete text editor so, i made these two code, but the first it's based on jtextpane and the second on a jeditorpane. I want to link toghether the second with the firt code , to have a cpmplete text editor. The problem is that i don't know how to do this. The fisrt think i thought to do was transform the jtext in the fisrt code in a jeditor but jeditor don't recognize the function 'append' .. Could someone help me? Thanks
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package GUI;
    import java.awt.Toolkit;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.StringSelection;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    import javax.swing.filechooser.FileNameExtensionFilter;
    * @author Elena
    public class Form extends javax.swing.JFrame {
    String ClipboardData = "";
    private Object CurrentFileDirectory;
    * Creates new form Form
    public Form() {
    initComponents();
    * 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() {
    jScrollPane2 = new javax.swing.JScrollPane();
    editorpane = new javax.swing.JEditorPane();
    jMenuBar1 = new javax.swing.JMenuBar();
    Open = new javax.swing.JMenu();
    New = new javax.swing.JMenuItem();
    Openfile = new javax.swing.JMenuItem();
    Save = new javax.swing.JMenuItem();
    SaveAs = new javax.swing.JMenuItem();
    Exit = new javax.swing.JMenuItem();
    Cut = new javax.swing.JMenu();
    jMenuItem6 = new javax.swing.JMenuItem();
    Copy = new javax.swing.JMenuItem();
    Paste = new javax.swing.JMenuItem();
    Delete = new javax.swing.JMenuItem();
    SelectAll = new javax.swing.JMenuItem();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Java Text Editor");
    jScrollPane2.setViewportView(editorpane);
    Open.setText("File");
    New.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
    New.setText("New");
    New.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    NewActionPerformed(evt);
    Open.add(New);
    Openfile.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
    Openfile.setText("Open...");
    Openfile.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    OpenfileActionPerformed(evt);
    Open.add(Openfile);
    Save.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
    Save.setText("Save");
    Save.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    SaveActionPerformed(evt);
    Open.add(Save);
    SaveAs.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
    SaveAs.setText("Save As...");
    SaveAs.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    SaveAsActionPerformed(evt);
    Open.add(SaveAs);
    Exit.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_0, java.awt.event.InputEvent.CTRL_MASK));
    Exit.setText("Exit");
    Exit.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    ExitActionPerformed(evt);
    Open.add(Exit);
    jMenuBar1.add(Open);
    Cut.setText("Edit");
    jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK));
    jMenuItem6.setText("Cut");
    jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jMenuItem6ActionPerformed(evt);
    Cut.add(jMenuItem6);
    Copy.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
    Copy.setText("Copy");
    Copy.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    CopyActionPerformed(evt);
    Cut.add(Copy);
    Paste.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
    Paste.setText("Paste");
    Paste.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    PasteActionPerformed(evt);
    Cut.add(Paste);
    Delete.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DELETE, 0));
    Delete.setText("Delete");
    Delete.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    DeleteActionPerformed(evt);
    Cut.add(Delete);
    SelectAll.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
    SelectAll.setText("Select All");
    SelectAll.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    SelectAllActionPerformed(evt);
    Cut.add(SelectAll);
    jMenuBar1.add(Cut);
    setJMenuBar(jMenuBar1);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 479, Short.MAX_VALUE)
    pack();
    }// </editor-fold>
    private void NewActionPerformed(java.awt.event.ActionEvent evt) {                                   
    editorpane.setText("");
    private void ExitActionPerformed(java.awt.event.ActionEvent evt) {                                    
    System.exit(0);
    private void DeleteActionPerformed(java.awt.event.ActionEvent evt) {                                      
    editorpane.replaceSelection("");
    private void SaveAsActionPerformed(java.awt.event.ActionEvent evt) {                                      
    JFileChooser sdChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX File", "txt");
    sdChooser.setFileFilter(filter);
    int returnVal = sdChooser.showSaveDialog(null);
    try{
    if(returnVal == JFileChooser.APPROVE_OPTION){
    File directory = sdChooser.getCurrentDirectory();
    String path = directory.getAbsolutePath();
    String fileName = sdChooser.getSelectedFile().getName();
    if(fileName.contains(".docx")){
    }else{
    fileName = fileName + ".docx";
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "\\" + fileName)));
    bw.write(editorpane.getText());
    bw.close();
    } catch(IOException e){
    JOptionPane.showMessageDialog(null, "ERROR!");
    private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {                                          
    ClipboardData = editorpane.getSelectedText();
    StringSelection stringSelection = new StringSelection(ClipboardData);
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(stringSelection, null);
    editorpane.replaceSelection("");
    private void CopyActionPerformed(java.awt.event.ActionEvent evt) {                                    
    ClipboardData = editorpane.getSelectedText();
    StringSelection stringSelection = new StringSelection(ClipboardData);
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(stringSelection, null);
    private void PasteActionPerformed(java.awt.event.ActionEvent evt) {                                     
    editorpane.append(ClipboardData);
    private void SelectAllActionPerformed(java.awt.event.ActionEvent evt) {                                         
    editorpane.selectAll();
    private void OpenfileActionPerformed(java.awt.event.ActionEvent evt) {                                        
    JFileChooser opChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX file", "docx");
    opChooser.setFileFilter(filter);
    int returnval = opChooser.showOpenDialog(null);
    File chosenFile = opChooser.getSelectedFile();
    try {
    if(returnval == JFileChooser.APPROVE_OPTION){
    BufferedReader br = new BufferedReader(new FileReader(chosenFile));
    editorpane.setText("");
    String data;
    while((data = br.readLine()) != null) {
    editorpane.append(data + "\n");}
    br.close();
    }catch(IOException e){
    JOptionPane.showMessageDialog(null, "ERROR!" );
    private void SaveActionPerformed(java.awt.event.ActionEvent evt) {                                    
    if("".equals(CurrentFileDirectory)){
    JFileChooser sdChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("DOCX file", "docx");
    sdChooser.setFileFilter(filter);
    int returnval = sdChooser.showOpenDialog(null);
    try{
    if(returnval == JFileChooser.APPROVE_OPTION){
    File directory = sdChooser.getCurrentDirectory();
    String path = directory.getAbsolutePath();
    String fileName = sdChooser.getSelectedFile().getName();
    if(fileName.contains(".docx")){
    }else{
    fileName = fileName + ".docx";
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "\\" + fileName)));
    bw.write(editorpane.getText());
    bw.close();}
    }catch(IOException e){     
    JOptionPane.showMessageDialog(null, "ERROR!");
    * @param args the command line arguments
    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(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    //</editor-fold>
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
    new Form().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JMenuItem Copy;
    private javax.swing.JMenu Cut;
    private javax.swing.JMenuItem Delete;
    private javax.swing.JMenuItem Exit;
    private javax.swing.JMenuItem New;
    private javax.swing.JMenu Open;
    private javax.swing.JMenuItem Openfile;
    private javax.swing.JMenuItem Paste;
    private javax.swing.JMenuItem Save;
    private javax.swing.JMenuItem SaveAs;
    private javax.swing.JMenuItem SelectAll;
    private javax.swing.JEditorPane editorpane;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GraphicsEnvironment;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Action;
    import javax.swing.JButton;
    import javax.swing.JColorChooser;
    import javax.swing.JComboBox;
    import javax.swing.JDialog;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.Element;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.StyledEditorKit;
    public class Colore {
    public Colore() {
    JFrame frame = new JFrame();
    JTextPane textPane = new JTextPane();
    JScrollPane scrollPane = new JScrollPane(textPane);
    JPanel north = new JPanel();
    JMenuBar menu = new JMenuBar();
    JMenu styleMenu = new JMenu();
    styleMenu.setText("Style");
    Action boldAction = new BoldAction();
    boldAction.putValue(Action.NAME, "Bold");
    styleMenu.add(boldAction);
    Action italicAction = new ItalicAction();
    italicAction.putValue(Action.NAME, "Italic");
    styleMenu.add(italicAction);
    Action foregroundAction = new ForegroundAction();
    foregroundAction.putValue(Action.NAME, "Color");
    styleMenu.add(foregroundAction);
    Action formatTextAction = new FontAndSizeAction();
    formatTextAction.putValue(Action.NAME, "Font and Size");
    styleMenu.add(formatTextAction);
    menu.add(styleMenu);
    north.add(menu);
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(north, BorderLayout.NORTH);
    frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
    frame.setSize(800, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    public static void main(String[] args) {
    new Culo();
    class BoldAction extends StyledEditorKit.StyledTextAction {
    private static final long serialVersionUID = 9174670038684056758L;
    public BoldAction() {
    super("font-bold");
    public String toString() {
    return "Bold";
    public void actionPerformed(ActionEvent e) {
    JEditorPane editor = getEditor(e);
    if (editor != null) {
    StyledEditorKit kit = getStyledEditorKit(editor);
    MutableAttributeSet attr = kit.getInputAttributes();
    boolean bold = (StyleConstants.isBold(attr)) ? false : true;
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setBold(sas, bold);
    setCharacterAttributes(editor, sas, false);
    class ItalicAction extends StyledEditorKit.StyledTextAction {
    private static final long serialVersionUID = -1428340091100055456L;
    public ItalicAction() {
    super("font-italic");
    public String toString() {
    return "Italic";
    public void actionPerformed(ActionEvent e) {
    JEditorPane editor = getEditor(e);
    if (editor != null) {
    StyledEditorKit kit = getStyledEditorKit(editor);
    MutableAttributeSet attr = kit.getInputAttributes();
    boolean italic = (StyleConstants.isItalic(attr)) ? false : true;
    SimpleAttributeSet sas = new SimpleAttributeSet();
    StyleConstants.setItalic(sas, italic);
    setCharacterAttributes(editor, sas, false);
    class ForegroundAction extends StyledEditorKit.StyledTextAction {
    private static final long serialVersionUID = 6384632651737400352L;
    JColorChooser colorChooser = new JColorChooser();
    JDialog dialog = new JDialog();
    boolean noChange = false;
    boolean cancelled = false;
    public ForegroundAction() {
    super("foreground");
    public void actionPerformed(ActionEvent e) {
    JTextPane editor = (JTextPane) getEditor(e);
    if (editor == null) {
    JOptionPane.showMessageDialog(null,
    "You need to select the editor pane before you can change the color.", "Error",
    JOptionPane.ERROR_MESSAGE);
    return;
    int p0 = editor.getSelectionStart();
    StyledDocument doc = getStyledDocument(editor);
    Element paragraph = doc.getCharacterElement(p0);
    AttributeSet as = paragraph.getAttributes();
    fg = StyleConstants.getForeground(as);
    if (fg == null) {
    fg = Color.BLACK;
    colorChooser.setColor(fg);
    JButton accept = new JButton("OK");
    accept.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    fg = colorChooser.getColor();
    dialog.dispose();
    JButton cancel = new JButton("Cancel");
    cancel.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    cancelled = true;
    dialog.dispose();
    JButton none = new JButton("None");
    none.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    noChange = true;
    dialog.dispose();
    JPanel buttons = new JPanel();
    buttons.add(accept);
    buttons.add(none);
    buttons.add(cancel);
    dialog.getContentPane().setLayout(new BorderLayout());
    dialog.getContentPane().add(colorChooser, BorderLayout.CENTER);
    dialog.getContentPane().add(buttons, BorderLayout.SOUTH);
    dialog.setModal(true);
    dialog.pack();
    dialog.setVisible(true);
    if (!cancelled) {
    MutableAttributeSet attr = null;
    if (editor != null) {
    if (fg != null && !noChange) {
    attr = new SimpleAttributeSet();
    StyleConstants.setForeground(attr, fg);
    setCharacterAttributes(editor, attr, false);
    }// end if color != null
    noChange = false;
    cancelled = false;
    private Color fg;
    class FontAndSizeAction extends StyledEditorKit.StyledTextAction {
    private static final long serialVersionUID = 584531387732416339L;
    private String family;
    private float fontSize;
    JDialog formatText;
    private boolean accept = false;
    JComboBox fontFamilyChooser;
    JComboBox fontSizeChooser;
    public FontAndSizeAction() {
    super("Font and Size");
    public String toString() {
    return "Font and Size";
    public void actionPerformed(ActionEvent e) {
    JTextPane editor = (JTextPane) getEditor(e);
    int p0 = editor.getSelectionStart();
    StyledDocument doc = getStyledDocument(editor);
    Element paragraph = doc.getCharacterElement(p0);
    AttributeSet as = paragraph.getAttributes();
    family = StyleConstants.getFontFamily(as);
    fontSize = StyleConstants.getFontSize(as);
    formatText = new JDialog(new JFrame(), "Font and Size", true);
    formatText.getContentPane().setLayout(new BorderLayout());
    JPanel choosers = new JPanel();
    choosers.setLayout(new GridLayout(2, 1));
    JPanel fontFamilyPanel = new JPanel();
    fontFamilyPanel.add(new JLabel("Font"));
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontNames = ge.getAvailableFontFamilyNames();
    fontFamilyChooser = new JComboBox();
    for (int i = 0; i < fontNames.length; i++) {
    fontFamilyChooser.addItem(fontNames);
    fontFamilyChooser.setSelectedItem(family);
    fontFamilyPanel.add(fontFamilyChooser);
    choosers.add(fontFamilyPanel);
    JPanel fontSizePanel = new JPanel();
    fontSizePanel.add(new JLabel("Size"));
    fontSizeChooser = new JComboBox();
    fontSizeChooser.setEditable(true);
    fontSizeChooser.addItem(new Float(4));
    fontSizeChooser.addItem(new Float(8));
    fontSizeChooser.addItem(new Float(12));
    fontSizeChooser.addItem(new Float(16));
    fontSizeChooser.addItem(new Float(20));
    fontSizeChooser.addItem(new Float(24));
    fontSizeChooser.setSelectedItem(new Float(fontSize));
    fontSizePanel.add(fontSizeChooser);
    choosers.add(fontSizePanel);
    JButton ok = new JButton("OK");
    ok.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    accept = true;
    formatText.dispose();
    family = (String) fontFamilyChooser.getSelectedItem();
    fontSize = Float.parseFloat(fontSizeChooser.getSelectedItem().toString());
    JButton cancel = new JButton("Cancel");
    cancel.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    formatText.dispose();
    JPanel buttons = new JPanel();
    buttons.add(ok);
    buttons.add(cancel);
    formatText.getContentPane().add(choosers, BorderLayout.CENTER);
    formatText.getContentPane().add(buttons, BorderLayout.SOUTH);
    formatText.pack();
    formatText.setVisible(true);
    MutableAttributeSet attr = null;
    if (editor != null && accept) {
    attr = new SimpleAttributeSet();
    StyleConstants.setFontFamily(attr, family);
    StyleConstants.setFontSize(attr, (int) fontSize);
    setCharacterAttributes(editor, attr, false);

    Sorry. My problem is that I want to insert HTML inside the body tag of an HTML page, and I don't know any simple method to get a reference to the <body> element from the JEditorPane widget, I get a reference to the actual HTML document but I can't get a reference of a tag from HTMLDocument either. Thanks.
    Juanjo

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

  • Layout with insertcomponent

    Hi all,
    I'm inserting components in a JTextPane using the insertComponent method.
    How can I use a layout with that? I want to have 2 items at the top and one at the bottom, when I resize my window, the components are shifted into one line
    Thanks a lot

    You don' use layout managers with a JTextPane. The text "flows" from one line to the next. A component is just considered part of the text.

  • Java refresh/update JTextPane

    I have my JTextPane text reading from an xml file, now I have updated my xml file how do I make the JTextPane refresh/update with that content?
    Thanks in advance,
    Dennis

    It's a bit long
    Actually it's not that it isn't working, it is I don;t know the best way to do it.
    package trunk.textConversation;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;              //for layout managers and more
    import java.awt.event.*;        //for action events
    public class Textconversation extends JPanel implements ActionListener {
         //The name of the user
         public static String name = "Guest";
         //The message of the user
         public static String message;
         //The text to output
         public static String[] initString;
         //The style the text will be in
         public static String[] initStyles = {"regular"};
         public static JFrame frame;
         private static final long serialVersionUID = 1L;
         //private String newline = "\n";
        protected static final String textFieldString = "JTextField";
        protected static final String buttonString = "JButton";
        protected JLabel actionLabel;
        public Textconversation() {
            setLayout(new BorderLayout());
            //Create a regular text field.
            JTextField textField = new JTextField(10);
            textField.setActionCommand(textFieldString);
            textField.addActionListener(this);
            //Create some labels for the fields.
            JLabel textFieldLabel = new JLabel();
            textFieldLabel.setLabelFor(textField);
            //Create a label to put messages during an action event.
            actionLabel = new JLabel("Type text in a field and press Enter.");
            actionLabel.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));
            //Lay out the text controls and the labels.
            JPanel textControlsPane = new JPanel();
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints c = new GridBagConstraints();
            textControlsPane.setLayout(gridbag);
            JLabel[] labels = {textFieldLabel};
            JTextField[] textFields = {textField};
            addLabelTextRows(labels, textFields, gridbag, textControlsPane);
            c.gridwidth = GridBagConstraints.REMAINDER; //last
            c.anchor = GridBagConstraints.WEST;
            c.weightx = 1.0;
            textControlsPane.add(actionLabel, c);
            textControlsPane.setBorder(
                    BorderFactory.createCompoundBorder(
                                    BorderFactory.createTitledBorder("Text Fields"),
                                    BorderFactory.createEmptyBorder(5,5,5,5)));
            //Create a text pane.
            JTextPane textPane = createTextPane();
            JScrollPane paneScrollPane = new JScrollPane(textPane);
            paneScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            paneScrollPane.setPreferredSize(new Dimension(250, 155));
            paneScrollPane.setMinimumSize(new Dimension(10, 10));
            //Put the editor pane and the text pane in a split pane.
            JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                                                  paneScrollPane,
                                                  textControlsPane);
            splitPane.setOneTouchExpandable(true);
            splitPane.setResizeWeight(0.5);
            JPanel rightPane = new JPanel(new GridLayout(1,0));
            rightPane.add(splitPane);
            rightPane.setBorder(BorderFactory.createCompoundBorder(
                            BorderFactory.createTitledBorder("Styled Text"),
                            BorderFactory.createEmptyBorder(5,5,5,5)));
            //Put everything together.
            JPanel leftPane = new JPanel(new BorderLayout());
            add(leftPane, BorderLayout.LINE_START);
            add(rightPane, BorderLayout.LINE_END);
        private void addLabelTextRows(JLabel[] labels, JTextField[] textFields, GridBagLayout gridbag, Container container) {
            GridBagConstraints c = new GridBagConstraints();
            c.anchor = GridBagConstraints.EAST;
            int numLabels = labels.length;
            for (int i = 0; i < numLabels; i++) {
                c.gridwidth = GridBagConstraints.RELATIVE; //next-to-last
                c.fill = GridBagConstraints.NONE;      //reset to default
                c.weightx = 0.0;                       //reset to default
                container.add(labels, c);
    c.gridwidth = GridBagConstraints.REMAINDER; //end row
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1.0;
    container.add(textFields[i], c);
    public static void textOutput() {
         Xmlreader.readElement();
         initString = new String[Xmlreader.conversation.length];
         for (int s = 0; s < Xmlreader.conversation.length; s++) {
              initString[s] = Xmlreader.conversation[s] + "\n";
    public void actionPerformed(ActionEvent e) {
         //After user clicked enter
    String prefix = "You typed \"";
    if (textFieldString.equals(e.getActionCommand())) {
    JTextField source = (JTextField)e.getSource();
    actionLabel.setText(prefix + source.getText() + "\"");
    message = source.getText();
    Xmlreader.addElement();
    } else if (buttonString.equals(e.getActionCommand())) {
    Toolkit.getDefaultToolkit().beep();
    public JTextPane createTextPane() {
         textOutput();
    JTextPane textPane = new JTextPane();
    textPane.setEditable(false);
    StyledDocument doc = textPane.getStyledDocument();
    addStylesToDocument(doc);
    try {
                   for (int i=0; i < initString.length; i++) {
    doc.insertString(doc.getLength(), initString[i],
    doc.getStyle(initStyles[0]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
    return textPane;
    protected void addStylesToDocument(StyledDocument doc) {
    //Initialize some styles.
    Style def = StyleContext.getDefaultStyleContext().
    getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = doc.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "SansSerif");
    Style s = doc.addStyle("italic", regular);
    StyleConstants.setItalic(s, true);
    s = doc.addStyle("bold", regular);
    StyleConstants.setBold(s, true);
    s = doc.addStyle("small", regular);
    StyleConstants.setFontSize(s, 10);
    s = doc.addStyle("large", regular);
    StyleConstants.setFontSize(s, 16);
    s = doc.addStyle("icon", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    ImageIcon pigIcon = createImageIcon("", "");
    if (pigIcon != null) {
    StyleConstants.setIcon(s, pigIcon);
    s = doc.addStyle("button", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    ImageIcon soundIcon = createImageIcon("", "");
    JButton button = new JButton();
    if (soundIcon != null) {
    button.setIcon(soundIcon);
    } else {
    button.setText("BEEP");
    button.setCursor(Cursor.getDefaultCursor());
    button.setMargin(new Insets(0,0,0,0));
    button.setActionCommand(buttonString);
    button.addActionListener(this);
    StyleConstants.setComponent(s, button);
    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path,
    String description) {
    java.net.URL imgURL = Textconversation.class.getResource(path);
    if (imgURL != null) {
    return new ImageIcon(imgURL, description);
    } else {
    System.err.println("Couldn't find file: " + path);
    return null;
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event dispatch thread.
    private static void createAndShowGUI() {
    //Create and set up the window.
    frame = new JFrame("Conversation");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Add content to the window.
    frame.add(new Textconversation());
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event dispatching thread:
    //creating and showing this application's GUI.
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    //Turn off metal's use of bold fonts
                        UIManager.put("swing.boldMetal", Boolean.FALSE);
                        createAndShowGUI();
    Message was edited by:
    Dennis56

  • HTML in a JTextPane

    I am displaying simple html in a JTextPane. I've built simple pages with <Input> tags, I load them in the JTextPane and it works - looks great. I can input into these fields, but my question is how can I programmatically get the entry values I've made?

    Hi Puce thanks for the comment.
    Actually I am never submitting this web pages - I created a component to display web pages and gather the resulting input into a Properties file. The purpose of this is to be able to create sophisticated setup/configuration screens (images, layout, etc) in J2SE using html, so like I said I'm never submitting the pages.
    Anyway, I worked out how to do what I needed - I subclassed the HTMLEditorKit and kind of hacked what it's doing. It's pointless, but pretty sweet.

Maybe you are looking for