JScrollPane, JPanel & Scrollable interface

Hello,
I recently did a little programming with a JPanel and mistakenly implemented the Scrollable interface with a JPanel when I did not need to. In the process I discovered something that has sparked my curiosity. I added a group of JLabels in a GridLayout to this Scrollable JPanel. I also set the horizontalalignment of the JLabels in the panel. When this was set the JPanel by itself rendered the Labels according to the alignment I had set. However when I put the panel in a JScrollPane, The alignment of the Labels was not rendered as I expected. The elements in the JPanel were always flush to the left, no matter what alignment I had constructed the label with.
Does anyone know why if you descended from a JPanel and implemented the Scrollable interface with that object, when you pass the object into a JScrollPane why you would lose the alignments of the JLabels in that Scrollable JPanel?
This is not pivotal information to me, but I am curious. If anyone knows the answer to this please let me know.
Thanks,
Dan Hughes

Dan,
I have no idea why this happens. I do know however that it is a great source of insanity when you really need to get a JScrollPane to behave itself. If ever you need to make a JPanel the client of a JScrollPane use null layout and absolute positioning, also setPreferredSize of the JPanel before adding components. When all components are added to the JPanel make the JPanel the client of a JScrollPane. Also at the very end of your code you will need this code to make the layout the scrollBars behave:
SwingUtilities.invokeLater(new Runnable()
public void run()
getViewport().setViewPosition(new Point(0,0));
JScrollPAINS were not named PAINS for no reason. This information probably seems mostly irrelevant, but if you are curious, or intend on programming in future with JScrollPane it is probably wise to keep this near by.

Similar Messages

  • Getting Autoscroll Interface to work with JScrollPane/JPanel

    I got drag and drop working with a JPanel extended class.
    JScrollPane -> JPanel
    My JPanel is a DropTarget. I want the viewable portion on that JPanel to have an Insets object associated with it. How would I do that?
    I originally associated the Insets object with the JPanel. Problem was that a lot of the JPanel can be obscured. So if the top is hidden it doesn't realize it is at the edge. I tried associating an Insets object with the JScrollPane and with the JScrollPane's JViewport with limited success. But I ran into similar errors. I may be on the right track with some of this. Not sure.
    I would appreciate any help if anyone has done this before.
    Regardless of the ways I am attempting, if you had a JScrollPane with a JPanel (and the JPanel was your DropTarget), how would you implement the autoscrolling? Esp. in regards to the Insets object?
    regards,
    Geoff Robinson

    The following code will autoscroll almost any drop target, not sure what insets you are talking about though.
        static int autoscrollMargin = 20;
        Insets autoscrollInsets = new Insets(0, 0, 0, 0);
        // AutoScroll methods.
        public void autoscroll(Point location)
            //System.out.println("mouse at " + location);
            int top = 0, left = 0, bottom = 0, right = 0;
            Dimension size = getSize();
            Rectangle rect = getVisibleRect();
            int bottomEdge = rect.y + rect.height;
            int rightEdge = rect.x + rect.width;
            if (location.y - rect.y <= autoscrollMargin && rect.y > 0) top = autoscrollMargin;
            if (location.x - rect.x <= autoscrollMargin && rect.x > 0) left = autoscrollMargin;
            if (bottomEdge - location.y <= autoscrollMargin && bottomEdge < size.height) bottom = autoscrollMargin;
            if (rightEdge - location.x <= autoscrollMargin && rightEdge < size.width) right = autoscrollMargin;
            rect.x += right - left;
            rect.y += bottom - top;
            scrollRectToVisible(rect);
        public Insets getAutoscrollInsets()
            Dimension size = getSize();
            Rectangle rect = getVisibleRect();
            autoscrollInsets.top = rect.y + autoscrollMargin;
            autoscrollInsets.left = rect.x + autoscrollMargin;
            autoscrollInsets.bottom = size.height - (rect.y + rect.height) + autoscrollMargin;
            autoscrollInsets.right = size.width - (rect.x + rect.width) + autoscrollMargin;
            return autoscrollInsets;
        }

  • JPanel Scrollable mimic Windows Explorer Icon View

    I am developing an image viewer application, and I want my thumbnail image JPanel to mimic MS Windows Explorer's layout in icon view. However, I have not been able to accomplish this. I have searched high and low, finding many others with my same problem, but no solution. To see exactly what I want to mimic, go to Windows Explorer and take a look at Icon View.
    Windows Explorer seems to be using a type of FlowLayout, and the icons get wrapped to the next line. If the number of icons exceeds the viewable space, the vertical scrollbar appears. Note that there is no horizontal scrolling; only vertical scrolling with the FlowLayout. If the user adjusts the SplitPane, then the layout adjusts the scrolling and icons accordingly.
    ============================================================
    QUESTION: How can I get my JPanel to mimic Windows Explorer Icon View?
    ============================================================
    10 Dukes to anyone who can get this to mimic Windows Explorer. Ideally the solution would not be too involved.
    P.S. I think it stinks that JPanel, by design, does not implement Scrollable Interface. Even then, it doesn't work the way I want it to with my FlowLayout and only vertical scrolling. Does anyone understand why it doesn't implement Scrollable, like JTextArea, JEditorPane, etc. do?
    Thanks
    Wayne

    Thanks camickr! I didn't try your layout manager since I managed to find another one which seems to do the trick as well. Here is the link from which I found it:
    http://groups.google.com/groups?selm=c43ovb%242db505%241%40ID-76750.news.uni-berlin.de&output=gplain
    It seems that in the source there is a small bug which is easy to fix. I think the boolean parameters in minimumLayoutSize and preferredLayoutSize should be changed.
    So in minimumLayoutSize():
    return computeSize(target, true);and in preferredLayoutSize():
    return computeSize(target, false);After that fix, it worked just fine for me.
    Here is the complete source (author Babu Kalakrishnan):
    import java.awt.*;
      * A modified version of FlowLayout that allows containers using this
      * Layout to behave in a reasonable manner when placed inside a
      * JScrollPane
      * @author Babu Kalakrishnan
    public class ModifiedFlowLayout extends FlowLayout
         public ModifiedFlowLayout()
             super();
         public ModifiedFlowLayout(int align)
             super(align);
         public ModifiedFlowLayout(int align, int hgap, int vgap)
             super(align, hgap, vgap);
         public Dimension minimumLayoutSize(Container target)
             return computeSize(target, false);
         public Dimension preferredLayoutSize(Container target)
             return computeSize(target, true);
         private Dimension computeSize(Container target, boolean minimum)
             synchronized (target.getTreeLock())
                 int hgap = getHgap();
                 int vgap = getVgap();
                 int w = target.getWidth();
             // Let this behave like a regular FlowLayout (single row)
             // if the container hasn't been assigned any size yet     
                 if (w == 0)
                     w = Integer.MAX_VALUE;
                 Insets insets = target.getInsets();
                 if (insets == null)
                     insets = new Insets(0, 0, 0, 0);
                 int reqdWidth = 0;
                 int maxwidth = w - (insets.left + insets.right + hgap * 2);
                 int n = target.getComponentCount();
                 int x = 0;
                 int y = insets.top;
                 int rowHeight = 0;
                 for (int i = 0; i < n; i++)
                     Component c = target.getComponent(i);
                     if (c.isVisible())
                         Dimension d =
                             minimum ? c.getMinimumSize() :      
                          c.getPreferredSize();
                         if ((x == 0) || ((x + d.width) <= maxwidth))
                             if (x > 0)
                                 x += hgap;
                             x += d.width;
                             rowHeight = Math.max(rowHeight, d.height);
                         } else
                             x = d.width;
                             y += vgap + rowHeight;
                             rowHeight = d.height;
                         reqdWidth = Math.max(reqdWidth, x);
                 y += rowHeight;
                 return new Dimension(reqdWidth+insets.left+insets.right, y);
    }

  • JSplitPane, JScrollPane, JPanel & resize

    My program has 2 nested JSplitpanes, that divide the screen in 4 parts like a cross.
    I added a JScrollPane to one of the quaters and added a JPanel to the JScrollPane. The JPanel uses a CardLayout since I want to switch the components that I show there.
    One of the components I show on the JPanel is a JTree. If I expand the tree the panel becomes scrollable to show the whole tree. This is what I want because I want to be able to view the whole tree.
    The problem is, that if I switch to another component on the panel the panel stays that large even though I just want it to have the visible size
    This is how the panel looks like before switching to the tree and expanding it:
    http://img272.imageshack.us/img272/8695/noscroll3zj.jpg
    This is how the panel looks like after switching to the tree, expanding it and switching back:
    http://img272.imageshack.us/img272/6690/scroll3ef.jpg
    I want to restore the panel to its initial state but I cannot figure out how. Please help.

    If I add a panel to the split pane (to make it card layout) I can't use it for scrolling anymoreThis simple example works for me:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SplitPaneCard extends JFrame
         JSplitPane splitPane;
         JPanel cards;
         public SplitPaneCard()
              splitPane = new JSplitPane();
              getContentPane().add(splitPane, BorderLayout.CENTER);
              JTextArea textArea1 = new JTextArea(5, 10);
              textArea1.setText("1\n2\n3\n4\n5\n6\n7");
              textArea1.setForeground( Color.RED );
              JScrollPane scrollPane1 = new JScrollPane( textArea1 );
              JTextArea textArea2 = new JTextArea(5, 10);
              textArea2.setText("1234567");
              textArea2.setForeground( Color.BLUE );
              JScrollPane scrollPane2 = new JScrollPane( textArea2 );
            cards = new JPanel( new CardLayout() );
            cards.add(scrollPane1, "red");
            cards.add(scrollPane2, "blue");
            splitPane.setRightComponent( cards );
              JPanel buttonPanel = new JPanel();
              getContentPane().add(buttonPanel, BorderLayout.SOUTH);
              JButton red = new JButton("Show Red Text Area");
              red.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                      CardLayout cl = (CardLayout)(cards.getLayout());
                      cl.show(cards, "red");
              buttonPanel.add(red);
              JButton blue = new JButton("Show Blue Text Area");
              blue.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent e)
                      CardLayout cl = (CardLayout)(cards.getLayout());
                      cl.show(cards, "blue");
              buttonPanel.add(blue);
         public static void main(String[] args)
              final SplitPaneCard frame = new SplitPaneCard();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
    }

  • JScrollPane, JPanel used to make a paint-like application

    I am new to swing. I need help with implementing a paint-like application using JScrollPane and JPanel.
    I have put a JPanel inside a JScrollPane.
    The size of JPanel exceeds preferred size of JScrollPane, and i can see the scrollbars, and can go up and down.
    Problem is, when i draw on the JPanel, i can see what i've drawn very clearly. Now if I scroll down, and then scroll back up, whatever i had previously drawn has been erased.
    let me put it in a simpler manner. suppose i have drawn a filled circle whose diameter is equal to the viewport size of the JScrollPane. Now i am scrolling down till i can see only the bottom half of the circle. When i scroll back up, the upper half of the circle has been erased.
    i think this is a newbie error, and i guess it'll have a textbook response, so i have not bothered to paste my entire code here. however, if it is required, please let me know.

    Sounds very much like you're painting outside the paint cycle. Read this,
    http://java.sun.com/products/jfc/tsc/articles/painting/
    When the user draws on the screen, you want to do one of two things (these being just the most obvious and easiest implementations). For raster operations you want to manipulate an Image; for vector operations you want to manipulate a collection of Shapes.
    Your paintComponent() method of the panel should simply draw the stored images and shapes to the supplied Graphics object as appropriate.
    If you paint to a Graphics object outside the paint cycle then it will all be erased when the paint cycle is next invoked.

  • JApplet ,JScrollPane, JPanel

    Hi,
    I have a class JTestPanel2 which extends JPanel, I have added a button to this class and overriden the paint method to draw some lines,
    In my JApplet, i create instance of Test class and add to the JSCrollPane, I add this JScrollPane to my JApplet content pane, the problem is i dont see the JButton on the screen , but when i click on some where i have added the JButton , i get the action performed event triggered,
    My layout for Test class is BorderLayout and i add the button to north,
    So what is the problem ..how can i solve it,
    Answere ASAP
    here is the code
    for JPAnel
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class JPanelTest2 extends JPanel implements ActionListener
         JPanel jp2 ;
         JButton jb;
         String message = "test";
         JPanelTest2()
              super();
              setLayout(new BorderLayout());
              jp2 = new JPanel();
              jb = new JButton("Okay");
              jb.addActionListener(this);
              jp2.add(jb);     
         setPreferredSize(new Dimension(400,400));
         add("North", jp2);
         jp2.setVisible(true)     ;
         public void paint(Graphics g)
    super.paintComponent(g);
    g.drawString(message, 200, 200);
    public void actionPerformed(ActionEvent ev)
         message = "change";
         repaint();
    Code for Applet
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class JPanelTest1 extends JApplet
         Container c ;
         public void init()
         c = getContentPane();
         c.setLayout(new BorderLayout());
    JPanelTest2 jp1= new JPanelTest2();
         JScrollPane js = new JScrollPane(jp1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
         js.getHorizontalScrollBar().setMaximum(500);
         js.getHorizontalScrollBar().setValue(0);
         setSize(400,400);
         c.add("North", js);
    Ashish

    Do not override the drawing for your main container JPanel. Instead place another JPanel instance into the layout of your containing JPanel and draw with that. That will contain the drawing of that panel to just the area contained in that sub panel, and then it won't mess up the drawing of the other items contained within the main panel.

  • Image NOT refreshing in jscrollpane/jpanel [source code included]

    Hello All,
    I am simply trying to show a large image inside a JScrollPane. I put several panels inside the main frame with a scrollpane and buttons in separate panels. On load, the image shows fine, but when I click Hide, the image doesn't refresh unless i drag another window (whether it is the command prompt window or a browser window or ANY window) over the main frame. The same thing happens when I click Show. After the image is hidden (or removed) and Show is clicked, the image doesn't refresh unless you roll another window over the image window.
    Why does this happen??? Can someone please help? Your help is greatly appreciated! ...I am using Textpad by the way.
    You may try running this by pasting my code, but the line where it says "tempScreenCaptureTest = imageLoad "ScreenCapture/data/ScreenCapture.jpg");" needs a real jpg image file (i used a screenshot of my own desktop) for you to see an image.
    // import classes
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.datatransfer.*;
    import javax.swing.*;
    public class ScreenCaptureTest extends JFrame implements ActionListener
         private static void main(String[] args)
              // Create an instance of the application
              ScreenCaptureTest mainFrame = new ScreenCaptureTest();
              mainFrame.setVisible(true);
         } // end of main
         // create window objects
         private JPanel panelCenter = new JPanel();
         private JPanel panelSouth = new JPanel();
         private JScrollPane scrollPane;
         private JButton buttonShow = new JButton("Show");
         private JButton buttonHide = new JButton("Hide");
         private JLabel tempScreenCaptureTest;
         public ScreenCaptureTest()
              // font properties
              Font mainFont = new Font(("Verdana"), Font.PLAIN, 16);
              // set window properties
              setTitle("Screen Capture");
              setSize(700, 700);
              setBackground(Color.white);
              setResizable(false);
              getContentPane().setLayout(new BorderLayout());
              // load the ScreenCaptureTest image into the scrollPane object
              tempScreenCaptureTest = imageLoad("ScreenCapture/data/ScreenCapture.jpg");
              // set Cancel properties
              buttonShow.setFont(mainFont);
              buttonShow.setForeground(Color.black);
              buttonShow.setBackground(Color.gray);
              buttonShow.setBounds(50, 260, 200, 50);
              buttonShow.addActionListener(this);
              panelSouth.add(buttonShow, BorderLayout.WEST);
              // set Clear properties
              buttonHide.setFont(mainFont);
              buttonHide.setForeground(Color.black);
              buttonHide.setBackground(Color.gray);
              buttonHide.setBounds(50, 260, 200, 50);
              buttonHide.addActionListener(this);
              panelSouth.add(buttonHide, BorderLayout.EAST);
              // set panel properties
              getContentPane().add(panelSouth, BorderLayout.SOUTH);
         } // end of constructor
         // loads an image into the JScrollPane
         private JLabel imageLoad(String filepath)
              // create a label
              Icon image = new ImageIcon(filepath);
              JLabel labelScreenCaptureTest = new JLabel(image);
              panelCenter.setLayout(new BorderLayout());
              // create a tabbed pane
              scrollPane = new JScrollPane();
              scrollPane.getViewport().add(labelScreenCaptureTest);
              panelCenter.add(scrollPane, BorderLayout.CENTER);
              // set panel properties
              getContentPane().add(panelCenter, BorderLayout.CENTER);
              return labelScreenCaptureTest;
         // ActionListener method()
         public void actionPerformed(ActionEvent event)
              if (event.getSource() == buttonShow) {
                   scrollPane.getViewport().add(tempScreenCaptureTest);
                   panelCenter.add(scrollPane, BorderLayout.CENTER);
                   getContentPane().add(panelCenter, BorderLayout.CENTER);
              } else if (event.getSource() == buttonHide) {
                   System.out.print(tempScreenCaptureTest);
                   scrollPane.getViewport().remove(tempScreenCaptureTest);
                   panelCenter.remove(scrollPane);
                   getContentPane().add(panelCenter);
    }

    I might as well add my problem while I'm here. I'm using a JPanel with an overridden paint() method to draw my image. I'm holding the image in a JScrollPane and setting the preferred size to the image's dimensions. The trouble is, the image takes time to load. I've used an ImageObserver but I'm having trouble making it repaint the image. I can make the scroll pane update it's scrollbar width and height by telling it to updateUI() but I can't make it redraw the image. I've tried everything but from debugging I can see that it always calls my getPreferredSize() method last then after resizing, it doesn't redraw the image. Even if I tell it to repaint after updating UI. I'm at a loss :/ Is there a special component for managing images as I haven't done much work with them?

  • 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));

  • Implementing a Scrollable JPanel

    Does anyone have any suggestions for making a JPanel scrollable? Apparently, simply placing the JPanel inside a JScrollPane doesn't work, since JPanel does not implement Scrollable. I guess the solution would be to implement a custom JScrollablePanel. Has anyone else come across this problem?
    Thanks.

    Ok - I figured it out - It's the FlowLayout that I'm
    using for the JPanel. It doesn't support wrapping.hmm, no, that's not it. FlowLayout is actually a simple/limited layout manager - it's preferred size is always calculated as though it should be on one line, but it will wrap if the panel's actual width is too small and it's height can accomodate more than 1 row. When you put a JPanel in a JScrollPane, the panel's preferred-size is used to size the panel, hence, a single line that goes on forever. The best solution is to subclass your JPanel and implement Scrollable - that is the whole reason that Scrollable exists, so that you can tell the JScrollPane how to scroll. Here's a sample that obviously only works with FlowLayout: import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ScrollablePanel extends JPanel implements Scrollable {
         public ScrollablePanel() {
              this(FlowLayout.LEFT);
         public ScrollablePanel(int flowLayoutType) {
              super(new FlowLayout(flowLayoutType));
         public ScrollablePanel(int flowLayoutType, int hgap, int vgap) {
              super(new FlowLayout(flowLayoutType, hgap, vgap));
         public Dimension getPreferredSize() {
              if (getParent() == null)
                   return getPreferredSize();
                    // calculate the preferred size based on the flow of components
              FlowLayout flow = (FlowLayout)getLayout();
              int w = getParent().getWidth();
              int h = flow.getVgap();
              int x = flow.getHgap();
              int rowH = 0;
              Dimension d;
              Component[] comps = getComponents();
              for (int i = 0; i < comps.length; i++) {
                   if (comps.isVisible()) {
                        d = comps[i].getPreferredSize();
                        if (x + d.width > w && x > flow.getHgap()) {
                             x = flow.getHgap();
                             h += rowH;
                             rowH = 0;
                             h += flow.getVgap();
                        rowH = Math.max(d.height, rowH);
                        x += d.width + flow.getHgap();
              h += rowH;
              return new Dimension(w, h);
         public Dimension getPreferredScrollableViewportSize() {
              return getPreferredSize();
         public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
              // shift the view so that you see the next logical page
              if (orientation == SwingConstants.HORIZONTAL) {
                   // this won't happen in this case since we never scroll horizontally
                   return visibleRect.width;
              return visibleRect.height;
         public boolean getScrollableTracksViewportHeight() {
              // only force the height if the preferred size is too short to fill the viewport
              return getPreferredSize().height < getParent().getHeight();
         public boolean getScrollableTracksViewportWidth() {
              // always force this panel's width to the viewport's width
    // this effectively disables horizontal scrolling
              return true;
         public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
              return 10;
         private static JScrollPane scroller;
         private static ScrollablePanel sp;
         public static void main(String[] args) {
              try {
                   SwingUtilities.invokeAndWait(new Runnable() {
                        public void run() {
                             sp = new ScrollablePanel(FlowLayout.LEFT, 20, 20);
                             scroller = new JScrollPane(sp);
                             final JButton button = new JButton("Add Label");
                             button.addActionListener(new ActionListener() {
                                  public void actionPerformed(ActionEvent e) {
                                       sp.add(new JLabel("HELLO"));
                                       scroller.validate();
                             JPanel content = new JPanel(new BorderLayout());
                             content.add(button, BorderLayout.NORTH);
                             content.add(scroller);
                             JFrame f = new JFrame("Test");
                             f.setContentPane(content);
                             f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                             f.setSize(600, 400);
                             f.setLocationRelativeTo(null);
                             f.setVisible(true);
              catch (Exception e) { e.printStackTrace(); }

  • JScrollPane, what is wrong with my code?

    Hi, I appreciated if you helped me(perhaps by trying it out yourself?)
    I wanted my JScrollPane to display what is drawn on my canvas (which may be large)by scrolling, but it says it doesn't need any vertical and horizontal scroll bars. Here is the code that has this effect
    import javax.swing.*;
    import java.awt.*;
    public class WhatsWrong extends JApplet{
    public void init(){
    Container appletCont = getContentPane();
    appletCont.setLayout(new BorderLayout());
    JPanel p = new JPanel();
    p.setLayout(new BorderLayout());
    p.add(new LargeCanvas(),BorderLayout.CENTER);
    int ver = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
    int hor = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    JScrollPane jsp = new JScrollPane(p,ver,hor);
    appletCont.add(jsp,BorderLayout.CENTER);
    class LargeCanvas extends Canvas{
    public LargeCanvas(){
    super();
    setBackground(Color.white);
    public void paint(Graphics g){
    g.drawRect(50,50,700,700);
    and the html code:
    <html>
    <body>
    <applet code="WhatsWrong" width = 300 height = 250>
    </applet>
    </body>
    </html>
    What shall I do?
    Thanks in advance.

    What is wrong with your code is that your class, LargeCanvas must implement the Scrollable interface in order to be scrolled by a JScrollPane.
    A comment regarding your use of Canvas and Swing components: The Java Tutorial recommends that you extend JPanel to do custom painting. Canvas is what they call a "heavyweight" component and they recommend not to mix lightweight (Swing) components and heavyweight components.
    There is a lot more information on custom painting on the Java Tutorial in the Lesson "Creating a GUI with Swing.

  • URGENT! Need help with scrolling on a JPanel!

    Hello Guys! I guess there has been many postings about this subject in the forum, but the postings I found there.... still couldn't solve my problem...
    So, straight to the problem:
    I am drawing some primitive graphic on a JPanel. This JPanel is then placed in a JScrollPane. When running the code, the scrollbars are showing and the graphic is painted nicely. But when I try to scroll to see the parts of the graphics not visible in the current scrollbarview, nothing else than some flickering is happening... No movement what so ever...
    What on earth must I do to activate the scroll functionality on my JPanel??? Please Help!
    And yes, I have tried implementing the 'Scrollable' interface... But it did not make any difference...
    Code snippets:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.util.*;
    public class FilterComp extends JPanel {//implements Scrollable {
      protected DefaultMutableTreeNode root;
      protected Image buffer;
      protected int lastW = 0;
      protected int origoX = 0;
      protected final StringBuffer sb = new StringBuffer();
    //  protected int maxUnitIncrement = 1;
      protected JScrollPane scrollpane = new JScrollPane();
       *  Constructor for the FilterComp object
       *@param  scrollpane  Description of the Parameter
      public FilterComp(JScrollPane scrollpane) {
        super();
    //    setPreferredSize(new Dimension(1000, 500));
        this.setBackground(Color.magenta);
    //    setOpaque(false);
        setLayout(
          new BorderLayout() {
            public Dimension preferredLayoutSize(Container cont) {
              return new Dimension(1000, 600);
        this.scrollpane = scrollpane;
        scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollpane.setPreferredSize( new Dimension( 500, 500 ) );
        scrollpane.getViewport().add( this, null );
    //    scrollpane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
        repaint();
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int w = getSize().width;
        if (w != lastW) {
          buffer = null;
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        if (root != null) {
          int h = getHeight(root);
          if (buffer == null) {
            buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D g3 = (Graphics2D) buffer.getGraphics();
            g3.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g3.setColor(Color.black);
            g3.setStroke(new BasicStroke(2));
            paint(g3, (w / 2) + origoX, 10, w / 2, root); 
          lastW = w;
          AffineTransform old = g2.getTransform();
          AffineTransform trans = new AffineTransform();
          trans.translate((w / 2) + origoX, (getHeight() - (h * 40)) / 2);
          g2.setTransform(trans);
          g2.drawImage(buffer, (-w / 2) + origoX, 0, null);
          g2.setTransform(old);
        updateUI();
       *  Description of the Method
       *@param  g  Description of the Parameter
      public void update(Graphics g) {
        // Call paint to reduce flickering
        paint(g);
       *  Description of the Method
       *@param  g2    Description of the Parameter
       *@param  x     Description of the Parameter
       *@param  y     Description of the Parameter
       *@param  w     Description of the Parameter
       *@param  node  Description of the Parameter
      private void paint(Graphics2D g2, int x, int y, int w, DefaultMutableTreeNode node) {
        if (node.getChildCount() == 2) {
          DefaultMutableTreeNode c1 = (DefaultMutableTreeNode) node.getChildAt(0);
          DefaultMutableTreeNode c2 = (DefaultMutableTreeNode) node.getChildAt(1);
          if (c1.getChildCount() == 0 && c2.getChildCount() == 0) {
            String s = c1.getUserObject().toString() + " " + node.getUserObject() + " " + c2.getUserObject();
            paint(g2, x, y, s);
          } else {
            g2.drawLine(x - (w / 2), y, x + (w / 2), y);
            Font f = g2.getFont();
            g2.setFont(new Font(f.getName(), Font.BOLD | Font.ITALIC, f.getSize() + 2));
            paint(g2, x, y, node.getUserObject().toString());
            g2.setFont(f);
            g2.drawLine(x - (w / 2), y, x - (w / 2), y + 40);
            g2.drawLine(x + (w / 2), y, x + (w / 2), y + 40);
            paint(g2, x - (w / 2), y + 40, w / 2, c1);
            paint(g2, x + (w / 2), y + 40, w / 2, c2);
        } else if (node.getChildCount() == 0) {
          paint(g2, x, y, node.getUserObject().toString());
       *  Description of the Method
       *@param  g2  Description of the Parameter
       *@param  x   Description of the Parameter
       *@param  y   Description of the Parameter
       *@param  s   Description of the Parameter
      private void paint(Graphics2D g2, int x, int y, String s) {
        y += 10;
        StringTokenizer st = new StringTokenizer(s, "\\", false);
        if (s.indexOf("'") != -1 && st.countTokens() > 1) {
          int sh = g2.getFontMetrics().getHeight();
          while (st.hasMoreTokens()) {
            String t = st.nextToken();
            if (st.hasMoreTokens()) {
              t += "/";
            int sw = g2.getFontMetrics().stringWidth(t);
            g2.drawString(t, x - (sw / 2), y);
            y += sh;
        } else {
          int sw = g2.getFontMetrics().stringWidth(s);
          g2.drawString(s, x - (sw / 2), y);
       *  Sets the root attribute of the FilterComp object
       *@param  root  The new root value
      public void setRoot(DefaultMutableTreeNode root) {
        this.root = root;
        buffer = null;
       *  Gets the root attribute of the FilterComp object
       *@return    The root value
      public DefaultMutableTreeNode getRoot() {
        return root;
       *  Gets the height attribute of the FilterComp object
       *@param  t  Description of the Parameter
       *@return    The height value
      private int getHeight(TreeNode t) {
        int h = 1;
        int c = t.getChildCount();
        if (c > 0) {
          if (c > 1) {
            h += Math.max(getHeight(t.getChildAt(0)), getHeight(t.getChildAt(1)));
          } else {
            h += getHeight(t.getChildAt(0));
        return h;
       *  Sets the x attribute of the FilterComp object
       *@param  x  The new x value
      public void setX(int x) {
        origoX = x;
       *  Gets the x attribute of the FilterComp object
       *@return    The x value
      public int getX() {
        return origoX;
       *  Gets the preferredScrollableViewportSize attribute of the FilterComp
       *  object
       *@return    The preferredScrollableViewportSize value
    //  public Dimension getPreferredScrollableViewportSize() {
    //    return getPreferredSize();
       *  Gets the scrollableBlockIncrement attribute of the FilterComp object
       *@param  r            Description of the Parameter
       *@param  orientation  Description of the Parameter
       *@param  direction    Description of the Parameter
       *@return              The scrollableBlockIncrement value
    //  public int getScrollableBlockIncrement(Rectangle r, int orientation, int direction) {
    //    return 10;
       *  Gets the scrollableTracksViewportHeight attribute of the FilterComp object
       *@return    The scrollableTracksViewportHeight value
    //  public boolean getScrollableTracksViewportHeight() {
    //    return false;
       *  Gets the scrollableTracksViewportWidth attribute of the FilterComp object
       *@return    The scrollableTracksViewportWidth value
    //  public boolean getScrollableTracksViewportWidth() {
    //    return false;
       *  Gets the scrollableUnitIncrement attribute of the FilterComp object
       *@param  r            Description of the Parameter
       *@param  orientation  Description of the Parameter
       *@param  direction    Description of the Parameter
       *@return              The scrollableUnitIncrement value
    //  public int getScrollableUnitIncrement(Rectangle r, int orientation, int direction) {
    //    return 10;
    }

    The Scrollable interface should be implemented by a JPanel set as the JScrollPane's viewport or scrolling may not function. Although it is said to be only necessary for tables, lists, and trees, without it I have never had success with images. Even the Java Swing Tutorial on scrolling images with JScrollPane uses the Scrollable interface.
    I donot know what you are doing wrong here, but I use JScrollPane with a JPanel implementing Scrollable interface and it works very well scrolling images drawn into the JPanel.
    You can scroll using other components, such as the JScrollBar or even by using a MouseListener/MouseMotionListener combination, but this is all done behind the scenes with the use of JScrollPane/Scrollable combination.
    You could try this approach using an ImageIcon within a JLabel:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Test extends JFrame {
         BufferedImage bi;
         Graphics2D g_bi;
         public Test() {
              super("Scroll Test");
              makeImage();
              Container contentPane = getContentPane();
              MyView view = new MyView(new ImageIcon(bi));
              JScrollPane sp = new JScrollPane(view);
              contentPane.add(sp);
              setSize(200, 200);
              setVisible(true);
         private void makeImage() {
              bi = new BufferedImage(320, 240, BufferedImage.TYPE_INT_ARGB);
              g_bi = bi.createGraphics();
              g_bi.setColor(Color.white);
              g_bi.fillRect(0,0,320,240);
              g_bi.setColor(Color.black);
              g_bi.drawLine(0,0,320,240);
         public static void main(String args[]) {
              Test test = new Test();
    class MyView extends JLabel {
         ImageIcon icon;
         public MyView(ImageIcon ii) {
              super(ii);
              icon = ii;
         public void paintComponent(Graphics g) {
              g.drawImage(icon.getImage(),0,0,this);
    }Robert Templeton

  • ScrollBars not showing up for the JPanel [urgent]

    Hi,
    I have a frame in which i have two nested split panes i.e one horizontal splitpane and in that i am having one more split pane on the right side and a JTree on the left side.In the second split pane (which is a vertical split) ,as a top component , i am setting a JScrollPane in which i am trying to display a JPanel which is having a lot of swing components in it.I want to see the scroll bars for this panel so that i can see all the components.Do i have to implement Scrollable interface for this panel to scroll in the ScrollPane.I don't know how to implement Scrollable interface.Can some body help me in resolving this?This is some what urgent.Any help will be highly appreciated.
    Thanks in advance.
    Ashok

    Thank you all for your replies.I added the scroll bar policy.The scroll bars are showing up but the components inside the Panel are not moving.I want the components to move when i am scrolling.Here is my code.In the code SeriesDescPanel, SeriesDescMapPanel are sub classes of JPanel.I am using null layout to add the components to these panels.
    public class MainWindow extends JFrame implements TreeExpansionListener
    public MainWindow()
    throws RemoteException
    // This code is automatically generated by Visual Cafe when you add
              // components to the visual environment. It instantiates and initializes
              // the components. To modify the code, only use code syntax that matches
              // what Visual Cafe can generate, or Visual Cafe may be unable to back
              // parse your Java file into its visual environment.
              //{{INIT_CONTROLS
              setJMenuBar(menuBar);
              setTitle("Series Maintenance");
              getContentPane().setLayout(new BorderLayout(0,0));
              setSize(667,478);
              setVisible(false);
              JSplitPane1.setDividerSize(1);
              JSplitPane1.setOneTouchExpandable(true);
              getContentPane().add(BorderLayout.CENTER, JSplitPane1);
              seriesMenu.setText("Series");
              seriesMenu.setActionCommand("Series");
              menuBar.add(seriesMenu);
              newSeriesGroupMenuItem.setText("New Series Group");
              newSeriesGroupMenuItem.setActionCommand("New Series Group");
              seriesMenu.add(newSeriesGroupMenuItem);
              newSeriesMenuItem.setText("New Series");
              newSeriesMenuItem.setActionCommand("New Series");
              seriesMenu.add(newSeriesMenuItem);
              seriesMenu.add(JSeparator1);
              serachMenuItem.setText("Search");
              serachMenuItem.setActionCommand("Search");
              seriesMenu.add(serachMenuItem);
              seriesMenu.add(JSeparator2);
              saveMenuItem.setText("Save");
              saveMenuItem.setActionCommand("Save");
              seriesMenu.add(saveMenuItem);
              seriesMenu.add(JSeparator3);
              exitMenuItem.setText("Exit");
              exitMenuItem.setActionCommand("Exit");
              seriesMenu.add(exitMenuItem);
              adminMenu.setText("Administration");
              adminMenu.setActionCommand("Administration");
              menuBar.add(adminMenu);
              bulkLoadMenuItem.setText("Bulk Load");
              bulkLoadMenuItem.setActionCommand("Bulk Load");
              adminMenu.add(bulkLoadMenuItem);
              drsMenuItem.setText("DRS override");
              drsMenuItem.setActionCommand("DRS override");
              adminMenu.add(drsMenuItem);
              helpMenu.setText("Help");
              helpMenu.setActionCommand("Help");
              menuBar.add(helpMenu);
              tutorialMenuItem.setText("Tutorial");
              tutorialMenuItem.setActionCommand("Tutorial");
              helpMenu.add(tutorialMenuItem);
              bulkLoadFormatMenuItem.setText("Bulk Load Format");
              bulkLoadFormatMenuItem.setActionCommand("Bulk Load Format");
              helpMenu.add(bulkLoadFormatMenuItem);
              aboutMenuItem.setText("About");
              aboutMenuItem.setActionCommand("About");
              helpMenu.add(aboutMenuItem);
    JSplitPane2 = new javax.swing.JSplitPane();
    upperPanel = new SeriesDescPanel();
    JScrollPane2 = new javax.swing.JScrollPane(upperPanel,
    ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    JScrollPane3 = new javax.swing.JScrollPane();
    JSplitPane2.setOrientation(0);
    JSplitPane2.setDividerSize(1);
    JSplitPane2.setOneTouchExpandable(true);
    JSplitPane1.setRightComponent(JSplitPane2);
    JSplitPane1.setLeftComponent(viewPane);
    viewPane.add(alphabeticPane);
    viewPane.add(searchDataPane);
    viewPane.setTitleAt(0,"All");
              viewPane.setTitleAt(1,"search");
    //JScrollPane1.setMinimumSize(new Dimension(126, 478));
    JSplitPane2.setTopComponent(JScrollPane2);
    //JScrollPane2.setMinimumSize(new Dimension(426, 409));
    JSplitPane2.setBottomComponent(JScrollPane3);
    lowerPanel = new SeriesDescMapPanel();
    seriesTreeModel = new SeriesTreeModel(SeriesMaintenanceUI.getSeriesGroupInfo());
    tickersTree.setModel(seriesTreeModel);
    alphabeticPane.getViewport().setView(tickersTree);
    //JScrollPane2.getViewport().setView(upperPanel);
    //JScrollPane2.setViewportView(upperPanel);
    //upperPanel.scrollRectToVisible(new Rectangle(upperPanel.getWidth(),
    //upperPanel.getHeight(),1,1));
    JScrollPane3.getViewport().setView(lowerPanel);
    //JSplitPane2.setPreferredSize(new Dimension(426,200));
    SeriesDescPanel upperPanel;
    SeriesDescMapPanel lowerPanel;
    SeriesTreeModel seriesTreeModel;
    SeriesTreeModel searchTreeModel;
    javax.swing.JSplitPane JSplitPane2;
    javax.swing.JScrollPane JScrollPane2;
    javax.swing.JScrollPane JScrollPane3;
    javax.swing.JTree tickersTree = new javax.swing.JTree();
    javax.swing.JTree searchTree = new javax.swing.JTree();
    javax.swing.JScrollPane alphabeticPane = new javax.swing.JScrollPane();
    javax.swing.JTabbedPane viewPane = new JTabbedPane(SwingConstants.BOTTOM);
    javax.swing.JScrollPane searchDataPane = new javax.swing.JScrollPane();
    //{{DECLARE_CONTROLS
         javax.swing.JSplitPane JSplitPane1 = new javax.swing.JSplitPane();
         javax.swing.JMenuBar menuBar = new javax.swing.JMenuBar();
         javax.swing.JMenu seriesMenu = new javax.swing.JMenu();
         javax.swing.JMenuItem newSeriesGroupMenuItem = new javax.swing.JMenuItem();
         javax.swing.JMenuItem newSeriesMenuItem = new javax.swing.JMenuItem();
         javax.swing.JSeparator JSeparator1 = new javax.swing.JSeparator();
         javax.swing.JMenuItem serachMenuItem = new javax.swing.JMenuItem();
         javax.swing.JSeparator JSeparator2 = new javax.swing.JSeparator();
         javax.swing.JMenuItem saveMenuItem = new javax.swing.JMenuItem();
         javax.swing.JSeparator JSeparator3 = new javax.swing.JSeparator();
         javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
         javax.swing.JMenu adminMenu = new javax.swing.JMenu();
         javax.swing.JMenuItem bulkLoadMenuItem = new javax.swing.JMenuItem();
         javax.swing.JMenuItem drsMenuItem = new javax.swing.JMenuItem();
         javax.swing.JMenu helpMenu = new javax.swing.JMenu();
         javax.swing.JMenuItem tutorialMenuItem = new javax.swing.JMenuItem();
         javax.swing.JMenuItem bulkLoadFormatMenuItem = new javax.swing.JMenuItem();
         javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
    Pl. help me in resolving this.
    Ashok

  • How to make JScrollPane scroll faster?

    Hi,
    I have tried to develop on a program to zoom in or zoom out the image�a graph which is plotted using the method draw from Graphics2D. In the program, I am given about 1000 points, which are supposed to be plotted one by one suing the draw method, which later form a graph.
    I have put the JPanel, where the output of the graph is displayed, into a JscrollPane to enable scrolling of large image. However, when I am trying to scroll the image, it happen to me that the scrolling is extremely slow. When I click at the scrolling bar to scroll down the image, it take some time before the image is scrolled down.
    My doubt will be is there any method to make the scrolling on the JscrollPane to become faster?does this involve double buffering?
    Thank you.

    This may not be the answer to your problem, but I thought I would throw it out there. One reason it might scroll slowly is because by default the JScrollPane only moves 1 pixel for every click of the scroll bar. You can adjust this by having your JPanel implement the Scrollable interface.
    Here is a code sample -
    // implement Scrollable interface
    public Dimension getPreferredScrollableViewportSize()
    return getPreferredSize();
    public int getScrollableBlockIncrement( Rectangle r, int orientation, int direction )
    return 10;
    public boolean getScrollableTracksViewportHeight()
    return false;
    public boolean getScrollableTracksViewportWidth()
    return false;
    public int getScrollableUnitIncrement( Rectangle r, int orientation, int direction )
    return 10;
    Whatever number you have your getScrollableUnitIncrement and getScrollableBlockIncrement methods return is how many pixels your component will scroll for each click of the scroll bar.
    Give this a try.

  • Movable components interacting with JScrollPane

    I am creating movable components. The class is designed as an extension to JPanel and contains a label and a textfield. The Panel responds to the mouse and moves itself around a JPanel which is inside the JScrollPane according to the user. This will eventially be a layout process so users of this program can make things look the way they want.
    I can't seem to get the JScrollPane to recognize when a component is moved outside it's immediate area and scroll. I'm looking through the archives but I am not running into answers because I don't know what to look for.
    Do I need to look at the scrollable interface? Do I need to throw an event which will notify the Scrollpane. Any hints or answer would be greatly appreciated!
    Here is my main class definition which may provide some clues:
    public static void main (String[] args) {
    JFrame view = new JFrame( "Testing" );
    JPanel mainPanel = new JPanel();
    JScrollPane scrollPane = new JScrollPane( mainPanel );
    mainPanel.add( new movablePanel( "Label", "Testing" ) );
    mainPanel.add( new MovablePanel( "Label", "Text" ) );
    view.getContentPane().add( scrollPane );
    view.validate();
    view.repaint();
    view.show();

    Here's what you should do.
    In your panel's mouseDragged or mouseMoved event handler, add:
    x = this.getLocation().x;
    y = this.getLocation().y;
    maxX = this.getLocation().x+this.getSize().width;
    maxY = this.getLocation().y+this.getSize().height;
    scrollminX = ScrollPane.getViewPort().getViewPosition().x
    scrollminY = ... getViewPosition().y
    scrollmaxX = scrollminX + ScrollPane.getViewPort().getExtentSize().width;
    scrollmaxY = scrollminY + ... getExtentSize().height
    now test to see if everything is in range

  • JScrollPane content vanishing

    Strangely enough I have a problem that I cannot figure out.
    Last night I had a working program using the following structure:
    contentPane (GridBagLayout)
    Within the content pane were a load of buttons and a JTextField.
    There were also two jPanels.
    The first contained a jScrollPane which in turn contained a JEditorPane
    The second contained another jScrollPane which in turn contained a JList
    I redid the layout so now I have:
    A jPanel containing a jSplitPane
    The jSplitPane contains two jPanels. Each of the jPanels containsone of the jScrollPanes from the previous code. One of the jPanels also now contains the JTextField whilst the other contains a new button that does nothing at the moment.
    My problem is this.
    The JTextField and the new button show up.
    The two jScrollPanes show up (tested by changing the background colour of this and the change shows up)
    The content of the jScrollPanes does not show up even though it is there (tested by dumping the content to System.out)
    Code below is all the setup stuff. There's quite alot and I started cutting it down but didn't want to lose anything so though the whole lot may be useful.
    public class Frame1 extends JFrame {
    JPanel contentPane;
    //initialise everything
    Interface_Server s;
    IfObject ifo;
    String nick = "";
    String serv = "";
    String msgWindowStart = "<html><body>";
    String msgWindowEnd = "</body></html>";
    String ucolour = "black";
    Calendar cal = Calendar.getInstance();
    java.util.List LocalUL = Collections.synchronizedList(new ArrayList());
    boolean isConnected = false;
    GridBagLayout gridBagLayout1 = new GridBagLayout();
    JPanel jPanel2 = new JPanel();
    GridBagLayout gridBagLayout4 = new GridBagLayout();
    JPanel jPanel1 = new JPanel();
    JButton Colour = new JButton();
    JButton Connect = new JButton();
    JButton Nick = new JButton();
    JButton Quit = new JButton();
    JSplitPane jSplitPane1 = new JSplitPane();
    JButton Send = new JButton();
    GridBagLayout gridBagLayout2 = new GridBagLayout();
    GridBagLayout gridBagLayout3 = new GridBagLayout();
    JScrollPane jScrollPane1 = new JScrollPane();
    JEditorPane MessageWindow = new JEditorPane();
    JPanel jPanel3 = new JPanel();
    JTextField UserInput = new JTextField();
    JPanel jPanel4 = new JPanel();
    GridBagLayout gridBagLayout5 = new GridBagLayout();
    JList UserList = new JList();
    JScrollPane jScrollPane2 = new JScrollPane();
    JButton Access = new JButton();
    TitledBorder titledBorder1;
    //Construct the frame
    public Frame1() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    //Component initialization
    private void jbInit() throws Exception {
    contentPane = (JPanel) this.getContentPane();
    titledBorder1 = new TitledBorder("");
    contentPane.setLayout(gridBagLayout1);
    this.setLocale(java.util.Locale.getDefault());
    this.setSize(new Dimension(640, 480));
    this.setTitle("gogoGadgetChat");
    contentPane.setBackground(new Color(212, 208, 199));
    contentPane.setBorder(BorderFactory.createLineBorder(Color.black));
    contentPane.setDebugGraphicsOptions(0);
    contentPane.setDoubleBuffered(true);
    contentPane.setMaximumSize(new Dimension(2147483647, 2147483647));
    contentPane.setMinimumSize(new Dimension(640, 480));
    contentPane.setPreferredSize(new Dimension(640, 480));
    jPanel2.setLayout(gridBagLayout4);
    Colour.setEnabled(false);
    Colour.setForeground(Color.black);
    Colour.setText("Colour");
    Colour.addActionListener(new Frame1_Colour_actionAdapter(this));
    Colour.addActionListener(new Frame1_Colour_actionAdapter(this));
    Connect.setText("Okay");
    Connect.setVerticalAlignment(SwingConstants.CENTER);
    Connect.addActionListener(new Frame1_Connect_actionAdapter(this));
    Connect.addActionListener(new Frame1_Connect_actionAdapter(this));
    Nick.setEnabled(false);
    Nick.setText("Nick");
    Nick.addActionListener(new Frame1_Nick_actionAdapter(this));
    Nick.addActionListener(new Frame1_Nick_actionAdapter(this));
    Quit.setText("Quit");
    Quit.addActionListener(new Frame1_Quit_actionAdapter(this));
    Quit.addActionListener(new Frame1_Quit_actionAdapter(this));
    jSplitPane1.setBackground(Color.lightGray);
    jSplitPane1.setBorder(null);
    jSplitPane1.setDoubleBuffered(false);
    jSplitPane1.setPreferredSize(new Dimension(524, 263));
    jSplitPane1.setContinuousLayout(false);
    jSplitPane1.setLeftComponent(jPanel3);
    jSplitPane1.setOneTouchExpandable(true);
    jSplitPane1.setRightComponent(jPanel4);
    jSplitPane1.setTopComponent(null);
    jPanel1.setMaximumSize(new Dimension(32767, 35));
    jPanel1.setMinimumSize(new Dimension(321, 35));
    jPanel1.setLayout(gridBagLayout2);
    Send.setEnabled(false);
    Send.setText("Send");
    Send.addActionListener(new Frame1_Send_actionAdapter(this));
    Send.addActionListener(new Frame1_Send_actionAdapter(this));
    jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    jScrollPane1.getViewport().setBackground(Color.red);
    jScrollPane1.setAutoscrolls(true);
    jScrollPane1.setBorder(BorderFactory.createLoweredBevelBorder());
    jScrollPane1.setOpaque(false);
    jScrollPane1.setPreferredSize(new Dimension(257, 236));
    MessageWindow.setBackground(Color.white);
    MessageWindow.setFont(new java.awt.Font("Dialog", 0, 12));
    MessageWindow.setForeground(Color.black);
    MessageWindow.setAlignmentX((float) 0.5);
    MessageWindow.setBorder(null);
    MessageWindow.setDebugGraphicsOptions(0);
    MessageWindow.setDoubleBuffered(true);
    MessageWindow.setMinimumSize(new Dimension(24, 24));
    MessageWindow.setPreferredSize(new Dimension(257, 236));
    MessageWindow.setCaretColor(Color.black);
    MessageWindow.setEditable(false);
    MessageWindow.setMargin(new Insets(3, 3, 3, 3));
    MessageWindow.setSelectedTextColor(Color.white);
    MessageWindow.setContentType("text/html");
    MessageWindow.setText("<html><body><font face=\"arial\" color=\"green\"><" + currentTime() + "> Enter a nickname to use</font></body></html>");
    jPanel3.setLayout(gridBagLayout3);
    UserInput.setBackground(Color.white);
    UserInput.setEnabled(true);
    UserInput.setFont(new java.awt.Font("Dialog", 0, 12));
    UserInput.setMaximumSize(new Dimension(2147483647, 25));
    UserInput.setMinimumSize(new Dimension(0, 25));
    UserInput.setNextFocusableComponent(Connect);
    UserInput.setPreferredSize(new Dimension(0, 25));
    UserInput.setInputVerifier(null);
    UserInput.setMargin(new Insets(0, 0, 0, 0));
    UserInput.setText("");
    jPanel4.setLayout(gridBagLayout5);
    UserList.setBackground(Color.white);
    UserList.setAutoscrolls(false);
    UserList.setBorder(BorderFactory.createLoweredBevelBorder());
    UserList.setMaximumSize(new Dimension(90, 100000));
    UserList.setMinimumSize(new Dimension(90, 235));
    UserList.setPreferredSize(new Dimension(90, 235));
    UserList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jScrollPane2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    jScrollPane2.getViewport().setBackground(Color.orange);
    Access.setText("Accessibility");
    Access.addActionListener(new Frame1_Access_actionAdapter(this));
    jPanel3.setBackground(SystemColor.menu);
    jPanel4.setBackground(SystemColor.control);
    contentPane.add(jPanel2, new GridBagConstraints(0, 0, 2, 1, 1.0, 2.0
    ,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
    jPanel2.add(jSplitPane1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
    ,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
    jSplitPane1.add(jPanel3, JSplitPane.LEFT);
    jPanel3.add(jScrollPane1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
    ,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
    jPanel3.add(UserInput, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0
    ,GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    jSplitPane1.add(jPanel4, JSplitPane.RIGHT);
    jPanel4.add(jScrollPane2, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
    ,GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
    jScrollPane2.add(UserList, null);
    jScrollPane1.add(MessageWindow, null);
    contentPane.add(jPanel1, new GridBagConstraints(0, 2, 2, 1, 1.0, 0.0
    ,GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
    jPanel1.add(Connect, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0
    ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 100, 5, 0), 0, 0));
    jPanel1.add(Colour, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0
    ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 0), 0, 0));
    jPanel1.add(Nick, new GridBagConstraints(2, 0, 1, 1, 1.0, 0.0
    ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 0), 0, 0));
    jPanel1.add(Quit, new GridBagConstraints(3, 0, 1, 1, 1.0, 0.0
    ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 0, 5, 0), 0, 0));
    jPanel1.add(Send, new GridBagConstraints(4, 0, 1, 1, 1.0, 0.0
    ,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 100), 0, 0));
    jSplitPane1.setDividerLocation(520);
    jPanel4.add(Access, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0
    ,GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0, 0, 0, 8), 0, 0));
    }

    Hi,
    you should try to add your Lists to the jScrollPane's viewport:
    jscrollPane.getViewPort().add(ComponentXYZ);
    In order to get real scrolling in there, consider to add a JPanel to the scrollPane and then add your components to the JPanel.
    You have to make your own JPanel component that implements the Scrollable interface:
    class ContainerPanel extends JPanel implements Scrollable
    public ContainerPanel() {
    public final boolean getScrollableTracksViewportHeight ()
    return false;
    public final boolean getScrollableTracksViewportWidth ()
    return false;
    public final Dimension getPreferredScrollableViewportSize()
    return getPreferredSize ();
    public final int getScrollableBlockIncrement (Rectangle visibleRect,
    int orientation,
    int direction)
    return 5;
    public final int getScrollableUnitIncrement (Rectangle visibleRect,
    int orientation,
    int direction)
    return 5;
    Hope this helps.
    Kind Regards,
    Mark

Maybe you are looking for