Linking 2 JScrollPanes

I am looking for a way of linking two JScrollBar types together.
So that if one JScrollBar is moved the corresponding movement in the other follows suit.
Example:
There is a JFrame with two JScrollPanes side by side acting as a viewport to their respective JTextPane's
condition: User moves down 10 lines in one JScrollPane
result: Both JScrollPanes move down 10 lines

They both work in roughly the same way although when you set the model to be the same there is no master. Thanks for the code snippet really helped.
The only thing is I don't want to set the value of the "slave" scrollbar but the change since they were linked, which will be done via a button. I think I will be able to achieve this by assessing the differences in value between the two scrollbars before they are linked and store it in an int.
Thanks for your help much appreciated.

Similar Messages

  • Need help with java browser "Back" button

    All:
    I'm trying to make the "Back" button in my Java web browser work. Any help would be greatly appreciated. Here is my code:
    import javax.swing.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.text.html.*;
    import javax.swing.text.*;
    public class Browser implements HyperlinkListener, ActionListener
    String source = "http://www.google.com";
    final String GO = "Go";
    final String Back = "Back";
    JEditorPane ep = new JEditorPane(); //a JEditorPane allows display of HTML & RTF
    JToolBar tb = new JToolBar(); //a JToolBar sits above the JEditorPane & contains
    JTextField tf = new JTextField(40); // the JTextField & go button
    JLabel address = new JLabel(" Address: ");
    JButton back = new JButton(Back);
    JButton go = new JButton(GO);
    BorderLayout bl = new BorderLayout();
    JPanel panel = new JPanel(bl);
    JFrame frame = new JFrame("Billy Wolfe's Browser");
    protected Vector history;
    public Browser()
    openURL(source); //this method (defined below) opens a page with address source
    ep.setEditable(false); //this makes the HTML viewable only in teh JEditorPane, ep
    ep.addHyperlinkListener(this); //this adds a listener for clicking on links
    JScrollPane scroll = new JScrollPane(ep); //this puts the ep inside a scroll pane
    panel.add(scroll,BorderLayout.CENTER); //adds the scroll pane to center of panel
    tf.setActionCommand(GO); //gives the ActionListener on tf a name for its ActionEvent
    tf.setActionCommand(Back);
    tf.addActionListener(this); //adds an ActionListener to the JTextField (so user can
    go.addActionListener(this); //use "Enter Key")
    tb.add(back); //this adds the back button to the JToolBar
    tb.add(address); //this adds the Label "Address:" to the JToolBar
    tb.add(tf); //this adds the JTextField to the JToolBar
    tb.add(go); //this adds the go button to the JToolBar
    panel.add(tb,BorderLayout.NORTH); //adds the JToolBar to the top (North) of panel
    frame.setContentPane(panel);
    frame.setSize(1000,900);
    frame.setVisible(true);
    }// end Browser()
    public void openURL(String urlString)
    String start = urlString.substring(0,4);
    if(!start.equals("http")) //adds "http://" to the URL if needed
    urlString = "http://"+urlString;
    }//end if
    try
    URL url = new URL(urlString);
    ep.setPage(url); //this sets the ep page to the URL page
    tf.setText(urlString); //this sets the JTextField, tf, to the URL
    catch (Exception e)
    { System.out.println("Can't open "+source+" "+e);
    }//end try-catch
    }//end openURL
    public void hyperlinkUpdate(HyperlinkEvent he) //this allows linking
    HyperlinkEvent.EventType type = he.getEventType();
    if(type == HyperlinkEvent.EventType.ACTIVATED)
    openURL(he.getURL().toExternalForm());
    history.add(he.getURL().toExternalForm());
    }//end hyperlinkUpdate()
    public void actionPerformed(ActionEvent ae) //for the GO and BACK buttons
    String command = ae.getActionCommand();
    if(command.equals(GO))
    openURL(tf.getText());
    history.add(tf.getText());
    //JOptionPane.showMessageDialog(null, "This is a test");
    if(command.equals(Back))
    try
    String lastURL = (String)history.lastElement();
    history.removeElement(lastURL);
    lastURL = (String)history.lastElement();
    // JOptionPane.showMessageDialog(null, lastURL);
    ep.setPage(lastURL);
    if (history.size() == 1)
    back.setEnabled(false);
    catch (Exception e)
    System.out.println("ERROR: Trouble fetching URL");}
    }//end actionPerformed()
    }// end Browser class

    Here it is. I need to be able to click the Back button and view the previous URL.
    import javax.swing.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.text.html.*;
    import javax.swing.text.*;
    public class Browser implements HyperlinkListener, ActionListener
    String source = "http://www.google.com";
    final String GO = "Go";
    final String Back = "Back";
    JEditorPane ep = new JEditorPane(); //a JEditorPane allows display of HTML & RTF
    JToolBar tb = new JToolBar(); //a JToolBar sits above the JEditorPane & contains
    JTextField tf = new JTextField(40); // the JTextField & go button
    JLabel address = new JLabel(" Address: ");
    JButton back = new JButton(Back);
    JButton go = new JButton(GO);
    BorderLayout bl = new BorderLayout();
    JPanel panel = new JPanel(bl);
    JFrame frame = new JFrame("Billy Wolfe's Browser");
    protected Vector history;
    public Browser()
    openURL(source); //this method (defined below) opens a page with address source
    ep.setEditable(false); //this makes the HTML viewable only in teh JEditorPane, ep
    ep.addHyperlinkListener(this); //this adds a listener for clicking on links
    JScrollPane scroll = new JScrollPane(ep); //this puts the ep inside a scroll pane
    panel.add(scroll,BorderLayout.CENTER); //adds the scroll pane to center of panel
    tf.setActionCommand(GO); //gives the ActionListener on tf a name for its ActionEvent
    tf.setActionCommand(Back);
    tf.addActionListener(this); //adds an ActionListener to the JTextField (so user can
    go.addActionListener(this); //use "Enter Key")
    tb.add(back); //this adds the back button to the JToolBar
    tb.add(address); //this adds the Label "Address:" to the JToolBar
    tb.add(tf); //this adds the JTextField to the JToolBar
    tb.add(go); //this adds the go button to the JToolBar
    panel.add(tb,BorderLayout.NORTH); //adds the JToolBar to the top (North) of panel
    frame.setContentPane(panel);
    frame.setSize(1000,900);
    frame.setVisible(true);
    }// end Browser()
    public void openURL(String urlString)
    String start = urlString.substring(0,4);
    if(!start.equals("http")) //adds "http://" to the URL if needed
    urlString = "http://"+urlString;
    }//end if
    try
    URL url = new URL(urlString);
    ep.setPage(url); //this sets the ep page to the URL page
    tf.setText(urlString); //this sets the JTextField, tf, to the URL
    catch (Exception e)
    { System.out.println("Can't open "+source+" "+e);
    }//end try-catch
    }//end openURL
    public void hyperlinkUpdate(HyperlinkEvent he) //this allows linking
    HyperlinkEvent.EventType type = he.getEventType();
    if(type == HyperlinkEvent.EventType.ACTIVATED)
    openURL(he.getURL().toExternalForm());
    history.add(he.getURL().toExternalForm());
    }//end hyperlinkUpdate()
    public void actionPerformed(ActionEvent ae) //for the GO and BACK buttons
    String command = ae.getActionCommand();
    if(command.equals(GO))
    openURL(tf.getText());
    history.add(tf.getText());
    //JOptionPane.showMessageDialog(null, "This is a test");
    if(command.equals(Back))
    try
    String lastURL = (String)history.lastElement();
    history.removeElement(lastURL);
    lastURL = (String)history.lastElement();
    // JOptionPane.showMessageDialog(null, lastURL);
    ep.setPage(lastURL);
    if (history.size() == 1)
    back.setEnabled(false);
    catch (Exception e)
    System.out.println("ERROR: Trouble fetching URL");}
    }//end actionPerformed()
    }// end Browser class

  • I have Yahoo mail. I want to add a hyperlink to emails. Your File tool in top bar has Send Link, but nothing happens. Yahoo says to use Format, but not there.

    As in someone's previous question, I used to be able to add a hyperlink from a website. On Yahoo help, they say to click the hyperlink button on the formatting toolbar. There is no formatting toolbar. On your top toolbar, under File, there is a Send Link. When I click on this, nothing happens. On the top toolbar, under Edit, the Copy, Cut and Paste are grayed out. Please let me know how I can add a hyperlink to my email. I tried to add one from an Amazon page, but did not see anything on the page to make it possible. Thanks in advance.
    Dorothy

    First thing...you made a mistake
    import javax.swing.JScrollPane;
    import javax.swing.JScrollBar;
    import javax.swing.*;When you import javax.swing.*; You automatically
    import JScrollPane & JScrollBar class, there's no
    need for you to re import again...
    That is not always a mistake. There are cases where it makes sense to do both (i.e., to import both '*' and a specific class name from that package at the same time). I believe the common example is:
    import java.awt.*;
    import java.util.*;
    import java.util.List;Now you can use "List" as a short name for "java.util.List", but must use "java.awt.List" in full for "java.awt.List" objects. If you just did:
    import java.awt.*;
    import java.util.*;Then you couldn't use List as a short name for anything--because it is ambiguous. You'd have to use both "java.awt.List" and "java.util.List" spelled out in full.
    Or, if you did:
    import java.awt.*;
    import java.util.*;
    import java.awt.List; // NOTE CHANGEThen "List" is short for "java.awt.List", and you must use "java.util.List" in full for "java.awt.List" objects.

  • Varying size of JScrollPane

    Hi.
    I hope you can help me figure out what's going on. I have a component that I've written that should display buttons vertically (it's a basis for an OutlookBar styled component).
    The component is based on a JPanel that is put in a JScrollPane and the buttons are added to the JPanel. The JPanel has a VerticalFlowLayout (a custom layout class).
    Now for the problem: Every time I adjust the size of the component so that a scroll bar should appear, the getPreferredSize() method of the JScrollPane returns a width that is lesser than it returns when the scroll bar is not visible! The weird thing is that the difference in the width is exactly the width of the scroll bar... but it doesn't make much sense since the width that is returned when the scroll bar is visible is less than the width that is returned when the scroll bar is not visible (it would make sense to have it the other way around!).
    Since my component needs to keep a consistent width this behavior is extremely annoying! Below you can find the code for the panel (and the needed layout) if you'd like to try this out, any help will be greatly appreciated:
    import javax.swing.*;
    import javax.swing.plaf.ComponentUI;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    * A panel that contains a set of operations that are displayed under a common
    * category name on a <code>OutlookBar</code>.
    * @version Revision:$ Date:$
    public class OutlookBarCategoryPanel extends JPanel
        protected JPanel m_contentPanel = new JPanel( new VerticalFlowLayout( 5 ) );
        private JScrollPane m_contentScrollPane = new JScrollPane( m_contentPanel,
                                                        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
         * Constructs a new <tt>OutlookBarCategoryPanel</tt> that is initially empty.
        public OutlookBarCategoryPanel()
            super( new BorderLayout() );
            m_contentPanel.setBackground( SystemColor.control );
            super.add( m_contentScrollPane, BorderLayout.CENTER );
         * If the <code>preferredSize</code> has been set to a
         * non-<code>null</code> value just returns it.
         * If the UI delegate's <code>getPreferredSize</code>
         * method returns a non <code>null</code> value then return that;
         * otherwise defer to the component's layout manager.
         * @return the value of the <code>preferredSize</code> property
         * @see #setPreferredSize
         * @see ComponentUI
        public Dimension getPreferredSize()
            Dimension size = super.getPreferredSize();
            if( size.width < m_contentScrollPane.getPreferredSize().width )
                size.width = m_contentScrollPane.getPreferredSize().width;
            return size;
         * Appends the specified component to the end of this container.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * Note: If a component has been added to a container that
         * has been displayed, <code>validate</code> must be
         * called on that container to display the new component.
         * If multiple components are being added, you can improve
         * efficiency by calling <code>validate</code> only once,
         * after all the components have been added.
         * @param     comp   the component to be added
         * @see #addImpl
         * @see #validate
         * @see #revalidate
         * @return    the component argument
        public Component add( Component comp )
            return m_contentPanel.add( comp );
         * Adds the specified component to the end of this container.
         * Also notifies the layout manager to add the component to
         * this container's layout using the specified constraints object.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * Note: If a component has been added to a container that
         * has been displayed, <code>validate</code> must be
         * called on that container to display the new component.
         * If multiple components are being added, you can improve
         * efficiency by calling <code>validate</code> only once,
         * after all the components have been added.
         * @param     comp the component to be added
         * @param     constraints an object expressing
         *                  layout contraints for this component
         * @see #addImpl
         * @see #validate
         * @see #revalidate
         * @see       LayoutManager
         * @since     JDK1.1
        public void add( Component comp, Object constraints )
            m_contentPanel.add( comp );
         * Adds the specified component to this container with the specified
         * constraints at the specified index.  Also notifies the layout
         * manager to add the component to the this container's layout using
         * the specified constraints object.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * Note: If a component has been added to a container that
         * has been displayed, <code>validate</code> must be
         * called on that container to display the new component.
         * If multiple components are being added, you can improve
         * efficiency by calling <code>validate</code> only once,
         * after all the components have been added.
         * @param comp the component to be added
         * @param constraints an object expressing layout contraints for this
         * @param index the position in the container's list at which to insert
         * the component; <code>-1</code> means insert at the end
         * component
         * @see #addImpl
         * @see #validate
         * @see #revalidate
         * @see #remove
         * @see LayoutManager
        public void add( Component comp, Object constraints, int index )
            m_contentPanel.add( comp, index );
         * Adds the specified component to this container at the given
         * position.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * Note: If a component has been added to a container that
         * has been displayed, <code>validate</code> must be
         * called on that container to display the new component.
         * If multiple components are being added, you can improve
         * efficiency by calling <code>validate</code> only once,
         * after all the components have been added.
         * @param     comp   the component to be added
         * @param     index    the position at which to insert the component,
         *                   or <code>-1</code> to append the component to the end
         * @return    the component <code>comp</code>
         * @see #addImpl
         * @see #remove
         * @see #validate
         * @see #revalidate
        public Component add( Component comp, int index )
            return m_contentPanel.add( comp, index );
         * Adds the specified component to this container.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * This method is obsolete as of 1.1.  Please use the
         * method <code>add(Component, Object)</code> instead.
         * @see add(Component, Object)
        public Component add( String name, Component comp )
            return m_contentPanel.add( name, comp );
         * Removes the specified button from the panel.  The reference that is sent as
         * a parameter needs to point to the same instance as the button that should actually
         * be removed (in other words, this method will not perform an equal() comparison).
         * @param button    a reference to the button that should be removed.
        public void remove( OutlookBarOperationButton button )
            m_contentPanel.remove( button );
         * Removes all operations that have the specified caption.
         * @param caption   the caption of the operation(s) that should be removed.
        public void removeOperation( String caption )
            Component[] components = m_contentPanel.getComponents();
            for( int i=0; i<components.length; i++ )
                Component component = components;
    if( component != null && component instanceof AbstractButton )
    if( ((AbstractButton)component).getText().equals( caption ) )
    m_contentPanel.remove( i );
    public static void main( String[] args )
    JFrame frame = new JFrame( "OutlookBarCategorButton" );
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.getContentPane().setLayout( new BorderLayout() );
    OutlookBarCategoryPanel obcp = new OutlookBarCategoryPanel();
    obcp.add( new OutlookBarOperationButton( "foo", new ImageIcon( "images/History24.gif" ) ) );
    obcp.add( new OutlookBarOperationButton( "bar", new ImageIcon( "images/Help24.gif" ) ) );
    obcp.add( new OutlookBarOperationButton( "foobar", new ImageIcon( "images/Cut24.gif" ) ) );
    obcp.add( new OutlookBarOperationButton( "index 2", new ImageIcon( "images/isl_faninn.png" ) ), 2 );
    frame.getContentPane().add( obcp, BorderLayout.WEST );
    frame.pack();
    frame.show();
    And here is the code for the VerticalFlowLayout class:
    import java.awt.*;
    * A layout manager that works like the default layout manager in swing
    * (FlowLayout) except that it arranges its components vertically instead
    * of horizontally.
    * @version $Revision: 1.1 $ $Date: 2003/03/11 13:37:38 $
    public class VerticalFlowLayout implements LayoutManager
        private int m_vgap;
         * Creates a new instance of the class with an initial vertical gap of 0
         * pixels.
        public VerticalFlowLayout()
            this( 0 );
         * Creates a new instance of the class with an initial vertical gap of
         * the specified number of pixels.
         * @param vgap  the number of pixels to use as a gap between
         *              components
        public VerticalFlowLayout( int vgap )
            m_vgap = vgap;
         * Lays out the container in the specified panel.
         * @param theParent the component which needs to be laid out
        public void layoutContainer( Container theParent )
            Insets insets = theParent.getInsets();
            int w = theParent.getSize().width - insets.left - insets.right;
            int numComponents = theParent.getComponentCount();
            if( numComponents == 0 )
                return;
            int y = insets.top;
            int x = insets.left;
            for( int i = 0; i < numComponents; ++i )
                Component c = theParent.getComponent(i);
                if( c.isVisible() )
                    Dimension d = c.getPreferredSize();
                    c.setBounds( x, y, w, d.height );
                    y += d.height + m_vgap;
         * Calculates the minimum size dimensions for the specified
         * panel given the components in the specified parent container.
         * @param theParent the component to be laid out
         * @see #preferredLayoutSize
        public Dimension minimumLayoutSize( Container theParent )
            Insets insets = theParent.getInsets();
            int maxWidth = 0;
            int totalHeight = 0;
            int numComponents = theParent.getComponentCount();
            for( int i = 0; i < numComponents; ++i )
                Component c = theParent.getComponent( i );
                if( c.isVisible() )
                    Dimension cd = c.getMinimumSize();
                    maxWidth = Math.max( maxWidth, cd.width );
                    totalHeight += cd.height;
            Dimension td = new Dimension( maxWidth + insets.left + insets.right,
                    totalHeight + insets.top + insets.bottom + m_vgap * numComponents );
            return td;
         * If the layout manager uses a per-component string,
         * adds the component <code>comp</code> to the layout,
         * associating it
         * with the string specified by <code>name</code>.
         * @param name the string to be associated with the component
         * @param comp the component to be added
        public void addLayoutComponent( String name, Component comp )
         * Removes the specified component from the layout.
         * @param comp the component to be removed
        public void removeLayoutComponent( Component comp )
         * Calculates the preferred size dimensions for the specified
         * panel given the components in the specified parent container.
         * @param theParent the component to be laid out
         * @see #minimumLayoutSize
        public Dimension preferredLayoutSize( Container theParent )
            Insets insets = theParent.getInsets();
            int maxWidth = 0;
            int totalHeight = 0;
            int numComponents = theParent.getComponentCount();
            for( int i = 0; i < numComponents; ++i )
                Component c = theParent.getComponent( i );
                if( c.isVisible() )
                    Dimension cd = c.getPreferredSize();
                    maxWidth = Math.max( maxWidth, cd.width );
                    totalHeight += cd.height;
            Dimension td = new Dimension( maxWidth + insets.left + insets.right,
                    totalHeight + insets.top + insets.bottom + m_vgap * numComponents );
            return td;

    You can use calligraphy/ art brush strokes, can you not? Some of them come with AI and you can find quite a few on ze interweb. You could even create your own, if need be.
    Mylenium

  • Calculate the rectangle size displayed in JScrollPane

    Hi,
    I am pasting a code below, What i want to get is the the rectangle of panel which will be displayed, so i can use g.setClip method to only paint that much portion of the JPanel
    Please copy the code compile it and run it, so u will come to know my problem..
    I want to dynamically setClip so the display is proper when the user scrolls.
    Ashish
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestDisplaySize extends JFrame
         JScrollPane scrollPane ;
         public TestDisplaySize()
              super("layered pane");
              this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              MyPanel panel = new MyPanel();
              scrollPane = new JScrollPane(panel);
              Container contentPane = this.getContentPane();
              contentPane.add(scrollPane, BorderLayout.CENTER);
              setSize(new Dimension(800,600));
              this.setVisible(true);
         class MyPanel extends JPanel
              public MyPanel()
         setPreferredSize(new Dimension(2000,600) );     
         this.setBackground(Color.white);
         this.setOpaque(true);
         public void paintComponent(Graphics g)
    super.paintComponent(g);
    g.setClip(0,0, 750,550);
    g.setColor(Color.blue);
    int x = 0;
    for(int i = 0; i < 60; i++)
         x +=60;
         g.drawLine(x, 0, x, 600);
         public static void main(String args[])
         new TestDisplaySize();
    }

    ash,
    Use this:
    super.paintComponent(g);
    Rectangle r = scrollPane.getViewport().getViewRect();
    g.setClip((int)r.getX(), (int)r.getY(), (int)r.getWidth(), (int)r.getHeight());
    g.setColor(Color.blue);--A
    PS: in future please see the "special tokens" link in the posting page for special tags that will make posted code format better.

  • JEditorPane inside JScrollPane flickers somethin awful

    I'm working on an instant messenger/chat application, and I've noticed that when there is 'heavy' traffic, the JEditorPane flickers quite badly. The following code demonstrates the problem:
    import javax.swing.*;
    import java.awt.*;
    public class Test extends JFrame {
      public Test() {
        JEditorPane jep = new JEditorPane("text/html", "");
        StringBuffer sb = new StringBuffer();
        JScrollPane jsp = new JScrollPane(jep);
        this.setSize(640,480);
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(jsp, BorderLayout.CENTER);
        this.setVisible(true);
        for(int i = 0; i < 200; i++) {
          sb.insert(0, i+"<br>");
          jep.setText(sb.toString());
      public static void main(String[] args) { new Test(); }
    }I'm using JEditorPane because it's easy to change I can use html tags to alter the font color/size/properties/etc.... As well, users can embed links which will then open in a browser. Is there a better way of doing this? I've tried setDoubleBuffered(true/false) on various combinations of components, using String concatenations, and setting the StringBuffer's initial length to a largish number (~5000). Nothing seems to alter the results. This problem occurs on linux and NT4 with jdks 1.3.0_002, 1.3.1, 1.4. If someone can help I'd be really grateful. I want the target jdk to be 1.3.1, so anything that came in with 1.4 isn't really an option.
    Thanks in advance,
    m

    Kurt,
    Thanks, I think that did the trick. I still have to put it into the chat app, but it works great with the test app. One thing, I do want the new text to be inserted at the top, not appended, so I changed the read statement to:
    jep.getEditorKit().read(new java.io.StringReader(i+"<br>"), doc, 0);and that throws an exception:java.lang.RuntimeException: Must insert new content into body element-
         at javax.swing.text.html.HTMLDocument$HTMLReader.generateEndsSpecsForMidInsert(HTMLDocument.java:1716)
         at javax.swing.text.html.HTMLDocument$HTMLReader.<init>(HTMLDocument.java:1692)
         at javax.swing.text.html.HTMLDocument$HTMLReader.<init>(HTMLDocument.java:1564)
         at javax.swing.text.html.HTMLDocument$HTMLReader.<init>(HTMLDocument.java:1559)
         at javax.swing.text.html.HTMLDocument.getReader(HTMLDocument.java:118)
         at javax.swing.text.html.HTMLEditorKit.read(HTMLEditorKit.java:237)
         at Test.<init>(Test.java:25)
         at Test.main(Test.java:38)but if I change position to 1 it works fine. Any explanation? The source for EditorKit says:
         * @param pos The location in the document to place the
         *   content >= 0.m

  • JScrollPane (containing an expanding JTextPane)

    I am writing a chatroom program using Swing, so I have this JScrollPane wrapping a JTextPane where all the messages (conversations) are displayed. When a new message comes up, the program inserts it at the end of the JTextPane's StyledDocument. This is when some strange things happen (regardless of where is the JScrollPane's view). In the beginning, it scrolls to the very bottom automatically whenever a new message is inserted. However, sometimes, after I do some random manual scrolling, it just stays at the same location regardless if there is a new message inserted. This is obviously not what I would want for my chatroom.
    Instead, I want these behaviours when a new message is added:
    1) The JScrollPane will scroll to the bottom if it was already at the bottom before the message was added.
    2) The JScrollPane's view will stay at the same location if the user was viewing something in the middle of the JTextPane (not at the bottom).
    Please tell me how I can do this. Thanks!

    Thanks for the link which has very nice info on auto-scrolling.
    However, that only solved half of my problems.
    I don't want it to scroll when the user is viewing somewhere not at the bottom of the JScrollPane, which was the case (2) that I was describing. Can you suggest how I can do that?

  • Linking two JFrames using JButton-very,very urgent

    Hello,
    I have two JFrames I created using javax.swing.I am new to ActionListener.The two classes are the frames.Could someone please link them for me?Their code is as follows:-
    1.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class rr extends JFrame
    JButton rest=new JButton("Ground Chilli-Restaurant");
    JButton spa=new JButton("Carribean Spa");
    JButton gift =new JButton("Antiquo-Gift Shop");
    JButton pool=new JButton("Poolside Parlour");
    JButton recep=new JButton("Reception");
    JButton th=new JButton("Travel House");
    public rr()
    super( "Welcome");
    setSize(370,270);
    setBackground(Color.RED);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel pane=new JPanel();
    pane.setBackground(Color.MAGENTA);
    GridLayout family=new GridLayout(3,3,10,10);
    pane.setLayout(family);
    pane.add(rest);
    pane.add(spa);
    pane.add(gift);
    pane.add(pool);
    pane.add(recep);
    pane.add(th);
    getContentPane().add(pane);
    setVisible(true);
    public static void main(String[] args)
    rr frame=new rr();
    and the others are:-
    2.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import javax.swing.event.MouseInputListener;
    public class spa extends JFrame
    String[] subs={"Welcome Cocktail","Body Massage","Steam Room","Children's Pool"};
    JList subList=new JList(subs);
    JRadioButton li=new JRadioButton("Executive service");
    JRadioButton oi=new JRadioButton("Economic Service");
    JButton ok=new JButton("Back");
    JButton can=new JButton("Continue");
    public spa()
    super("The Carribean Spa");
    setBackground(Color.RED);
    setSize(230,400);
    JPanel panel=new JPanel();
    panel.setBackground(Color.PINK);
    JLabel label1=new JLabel("Kindly select from our services :-");
    JLabel label2=new JLabel("Which type of service would you like?");
    panel.add(label1);
    subList.setVisibleRowCount(8);
    JScrollPane scroller=new JScrollPane(subList);
    panel.add(scroller);
    panel.add(label2);
    panel.add(li);
    panel.add(oi);
    panel.add(ok);
    panel.add(can);
    getContentPane().add(panel);
    setVisible(true);
    public static void main(String[] arguments)
    spa app=new spa();
    3.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class op extends JFrame
    JProgressBar current;
    JTextArea out;
    JButton ok=new JButton("OK");
    JButton con=new JButton("View our Credits Board.");
    JButton find;
    Thread runner;
    int num=0;
    public op()
    super("Calculatiing your Hotel Bill.Please wait.");
    setSize(222,500);
    setBackground(Color.PINK);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    getContentPane().setLayout(new FlowLayout());
    current=new JProgressBar(2,2000);
    current.setValue(0);
    getContentPane().add(ok);
    getContentPane().add(con);
    current.setStringPainted(true);
    getContentPane().add(current);
    public void iterate()
    while(num<2000)
    current.setValue(num);
    try{
    Thread.sleep(1200);
    }catch(InterruptedException e){}
    num+=95;
    public static void main(String[] arg)
    op frame=new op();
    frame.pack();
    frame.setVisible(true);
    frame.iterate();
    and so on......
    Please link these frames for me as I am not fully familiar with ActionListener () and WindowListener().
    Thanks,
    Bala

    If you have work you urgently need done then you should pay someone to do it.
    This is not a charity work forum. This is a forum for getting guidance and advice.
    So you are in the wrong place. Go elsewhere.

  • Repainting a JScrollPane

    Hi everyone,
    I've search the forum for an answer to this question but I can't seem to find the solution to my problem.
    I have a loop which updates the contents of a JTextArea with some text. The JtextArea is inside a JScrollPane. When I add text to the JTextArea i used the .paintImmediately method to paint the string in the JTextArea so it is visible during execution (otherwise the text is not displayed until the loop has finished and the GUI is repainted).
    However, once the text has filled more than the visible rows, the JScrollPane doesn't scoll down so that you can see the new text., in fact, no scroll bar is displayed even though there is more text than is visible in the JTextArea. Only when the loop has finsihed executing does the scrollbar become visible. Does anyone know how to get around this problem so that each time a new line of text is added the scrollpane will automatically scroll to the bottom?
    I've made this example class to demonstrate my problem:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class TextArea extends JFrame {
        public static Container contentPane;
        public static JTextArea bodyField;
        public static JScrollPane bodyScroll;
        public static JButton generate;
        public static void main (String args[])
            TextArea textArea = new TextArea();
            textArea.pack();
            textArea.show();
        public TextArea()
             * Button
            JPanel generatePanel = new JPanel();
            generatePanel.setLayout(new BoxLayout(generatePanel, BoxLayout.X_AXIS));
            generatePanel.setAlignmentX(JComponent.LEFT_ALIGNMENT);
            generatePanel.add( Box.createRigidArea(new Dimension(5, 5) ) );
            generate = new JButton( "Generate" );
            generate.setMnemonic('G');
            generate.setToolTipText("Generare the link pages for your website");
            generate.addActionListener(new ActionListener() {
                public void actionPerformed(final ActionEvent e) {
                    Update update = new Update();
                    update.run();
            generatePanel.add( generate );
             * Body
            JPanel bodyPanel = new JPanel();
            bodyPanel.setLayout(new BoxLayout(bodyPanel, BoxLayout.X_AXIS));
            bodyPanel.setAlignmentX(JComponent.LEFT_ALIGNMENT);
            bodyPanel.setPreferredSize( new Dimension(700, 600) );
            bodyPanel.setMaximumSize( bodyPanel.getPreferredSize() );
            bodyField = new JTextArea();
            bodyScroll = new JScrollPane( bodyField );
            bodyScroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
            bodyPanel.add( Box.createRigidArea(new Dimension(5, 5) ) );
            bodyPanel.add( bodyScroll );
            JPanel mainMainPanel = new JPanel();
            mainMainPanel.setLayout(new BoxLayout(mainMainPanel, BoxLayout.Y_AXIS));
            mainMainPanel.setAlignmentX(JComponent.LEFT_ALIGNMENT);
            mainMainPanel.add( Box.createRigidArea(new Dimension(5, 5) ) );
            mainMainPanel.add( generatePanel );
            mainMainPanel.add( Box.createRigidArea(new Dimension(5, 5) ) );
            mainMainPanel.add( bodyPanel );
            JPanel mainPanel = new JPanel();
            mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
            mainPanel.setAlignmentX(JComponent.LEFT_ALIGNMENT);
            mainPanel.add( Box.createRigidArea(new Dimension(5,0)) );
            mainPanel.add( mainMainPanel );
            contentPane = this.getContentPane();
            contentPane.add( new JScrollPane( mainPanel ) );
        static class Update extends Thread
            public void run()
                for ( int i = 0; i < 50; i++ )
                    bodyField.append( i + "\n" );
                    bodyField.paintImmediately( bodyField.getBounds() );
                    bodyScroll.paintImmediately( bodyScroll.getBounds() );
    }

    sorry, I posted this again by accident. Please don't reply to it

  • Invisible JTextArea in a JScrollPane

    I want to have an invisible JTextArea in a JScrollPane (i only want a thin border either vieport border or JTextArea border). i tried setOpaque(false) for JTextArea, JScrollPane and both, and it wont work, i dont know why. Could anyone help me?

    This poster is 0 for 3 in responding to previous postings he has made.I did notice - that's why I didn't post the link.
    he/she might now learn how to do a search (for when future questions are ignored)
    What do you think the chances are he'll bother to thank anyone for the help
    he received on this posting?Nil
    a 'thank you' does go a long way to getting the next query answered, but I'd prefer just
    an acknowledement of "it works/doesn't work" - makes it so much easier, when
    searching the forums, when you spot a "yes, that works" at the end.

  • JEditor Pane & Html links

    Hello! I'm using a JEditorpane to display a HTML page but i'm experiencing the following problem:
    * I'm using images as links but link fonctionality only appears in some parts of the image, not all over it.
    I create the html code in a String :
    String code ="<a href=""><img ...></img></a>";
    and then
    jEditorPane.setText(code);
    Do you know what is happening??
    thanks!

    I used JTextPane, and it worked correctly, the only headache was Java's HTML rendering engine, which sucks.
    Anyway, try a code like this:
    JTextPane pa=new JTextPane();
    JScrollPane scroller=new JScrollPane(pa);
    TheComponentYouWantToDisplayTheRenderer.add(scroller);
    pa.setEditable(false);
    pa.setEditorKit(pa.createEditorKitForContentType("text/html"));
    // Here you can set the page you want to display
    // Unfortunately there is no progress meter,
    // you need to work around it...
    pa.setPage("http://java.sun.com/");If you want to follow links, you have to add a HyperlinkListener to the page, like this:
    pa.addHyperlinkListener(new Hyperactive());
    class Hyperactive implements HyperlinkListener {
         public void hyperlinkUpdate(HyperlinkEvent e) {
              if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                   if (e.getSource()==null) return;
                   JEditorPane pane = (JEditorPane) e.getSource();
                   if (e instanceof HTMLFrameHyperlinkEvent) {
                        HTMLFrameHyperlinkEvent  evt = (HTMLFrameHyperlinkEvent)e;
                        HTMLDocument doc = (HTMLDocument)pane.getDocument();
                        doc.processHTMLFrameHyperlinkEvent(evt);
                   } else {
                        try {
                             pane.setPage(e.getURL());
                        } catch (Throwable t) {
                             //t.printStackTrace();
    }I found this code in one of the tutorials, but it was long ago, and I don't remember which was it... :-)
    After this, you shouldn't have problems. But not that the img tag doesn't need to be closed, so try
    <img src="imgsrc">
    instead of
    <img src="imgsrc"></img>

  • How to display only a text in a string as a link??

    Hi All,
    In my application I have a datagrid. In 1 column of the datagrid I am populating messages which are posted from user. My problem is i have to search for a particualr text in all the messages and if it is there then i have to display as a link/linkbutton/button.
    Could you please let me know how can i do this
    Thanks

    Here is the solution that should work for any size text and any maximum width. This solution will lock the JTextPane to the maximum width while allowing the dialog height to grow to fit the text.
    import javax.swing.*;*
    import java.awt.*;
    public class FooDialog extends JDialog{
       public static void main(String args[]) {
          final int MAX_WIDTH = 256;
          //build the dialog
          FooDialog dialog = new FooDialog();
          JTextPane textPane = new JTextPane();
          textPane.setEditable(false);
          textPane.setText(
          "FOOBAR FOOBAR FOOBAR FOOBAR FOOBAR FOOBAR FOOBAR FOOBAR FOOBAR");
          JScrollPane scrollPane =
             new JScrollPane(textPane,
                                      JScrollPane.VERTICAL_SCROLLBAR_NEVER,
                                      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
          scrollPane.setBorder(null);
          scrollPane.setPreferredSize(new Dimension(MAX_WIDTH, 0));
          dialog.add(scrollPane, BorderLayout.CENTER);
          //show the dialog
          dialog.pack();
          JViewport viewport = scrollPane.getViewport();
          viewport.doLayout();
          scrollPane.setPreferredSize(viewport.getViewSize());
          dialog.pack();
          dialog.setVisible(true);
    }The first pack() will lay out the dialog, but the viewport.doLayout() will insure that the JTextPane is laid out. (Which rarely happens with the first pack() alone.) The last pack() re-lays out the dialog with the JScrollPane 's new preferred size--the view size that the JTextPane became during the viewport.doLayout() .

  • Select links within applet?

    I want to be able to acually select links etc.. From inside a java applet. Up to now i have managed to get it to display the website but it doesn't allow me to select the actual links and thus progress.
    private JEditorPane htmlPage;
    private JScrollPane htmlScroll;
    htmlPage = new JEditorPane;
    getThePage("http://www.APage.net");
    c.add(htmlScroll = new JScrollPane(htmlPage), BorderLayout.CENTER);
    private void getThePage(String location) {
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    try {
         htmlPage.setPage(location);
    catch (IOException io) {
    JOptionPane.showMessageDialog(this, "Page could not be
    found," + "\nPlease check your connection",
    "No connection", JOptionPane.WARNING_MESSAGE);
    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }//End meth
    Also will i still get pop-ups from sites with muliple pages or will only the main page be selected?

    Make sure the page is completely loaded before clicking on anything..
    Next use the zoom in feature to get a better angle at it
    If these two steps fail try refreshing the page and then trying.

  • Problem in setting desired position for JPanel in JScrollPane!!!

    Dear Friends,
    I am having problem to set desired Scrollable(JScrollPane) JPanel position. I have a JPanel in a JFrame which is scrolable with lot of objects. It automatically displays on the top position inside JScrollPane, I want to set scroll position on the middle for the panel.
    I went through the search for the same in this forum, i found some posts related to this but they are linked with JTextArea(setCaretPosition). With JPanel i can't set caret position.
    Could anyone guide me how to set the scroll position on middle.
    Regards..
    Jayshree

    Replace:
    if(view.getValueAt(row,column) instanceof ImageIcon){
            ((Component)view.getColumnModel().getColumn(column).getCellRenderer().
            getTableCellRendererComponent(view,view.getValueAt(row,column),true,true,row,column)).setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
          else
            ((Component)view.getColumnModel().getColumn(column).getCellRenderer().
            getTableCellRendererComponent(view,view.getValueAt(row,column),true,true,row,column)).setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
          }with:
    if(view.getValueAt(row,column) instanceof ImageIcon)
            view.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
          else
           view.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

  • How can I active link in JEditorPane

    I wana active my link on README.HTML file to going up down in my file or go to another html file here is my code:
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    public class EditorPaneEx
         public EditorPaneEx()
              JEditorPane editorPane1 = new JEditorPane();
              editorPane1.setEditable(false);
              java.net.URL helpURL = TextSamplerDemo.class.getResource("README.html");
              if (helpURL != null)
                   try
                        editorPane1.setPage(helpURL);
                   catch (IOException e)
                        System.err.println("Attempted to read a bad URL: " + helpURL);
              else
                   System.err.println("Couldn't find file: README.html");
                   editorPane1.setText("Error. Unable to load README.html file.");
              JScrollPane editorScrollPane = new JScrollPane(editorPane1);
              editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              editorScrollPane.setPreferredSize(new Dimension(250, 145));
              editorScrollPane.setMinimumSize(new Dimension(10, 10));
         //     JEditorPane editorPane2 = new JEditorPane("text/html", "<b>Help</b>");
         //     editorPane2.setEditable(false);
              JFrame aFrame = new JFrame("JScrollPane TEST");
              aFrame.setSize(400, 350);
    //          aFrame.getContentPane().add(editorPane2, BorderLayout.NORTH);
               aFrame.getContentPane().add(editorScrollPane);
               aFrame.setVisible(true);
               aFrame.setLocationRelativeTo(null);
               aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          public static void main(String[] args)
              new EditorPaneEx();
    }          I must input somthing like this:
    class Hyperactive implements HyperlinkListener {
    public void hyperlinkUpdate(HyperlinkEvent e) {but I can't understand how exacly make it work, plz If someone know the solution send the code. thank you for your time.

    Read the API for example code.

Maybe you are looking for