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

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

  • JSplitPane, JScrollPane and JTree resizing

    Hi,
    In a JSplitPane, I have, in the left part, a JScrollPane, containing a JTree and, in the right part, I have an other panel.
    When I click on different nodes in the JTree, the width of the left part changes, so the JSplitPane separator moves. How to avoid that ? I would prefer a scrolling move inside the JScrollPane !
    I am using JDK 1.3
    Thanks
    Olivier Scalbert

    Try to define the JScrollPane as
    public JScrollPane(Component view, int vsbPolicy, int hsbPolicy)
    Use vsbPolicy and hsbPolicy like the VERTICAL_SCROLLBAR_AS_NEEDED
    HORIZONTAL_SCROLLBAR_AS_NEEDED respectively.
    Then define the setPreferredSize to your JScrollPane. This preferredSize must be smaller than the size of the Component view if you want to see the ScrollBar.
    By the way, when you define your JSplitPane have to define the setOneTouchExpandable(true);?

  • JTabbedPane/JSplitPane/JScrollPane problem

    Hi
    I'm making a simple webbrowser with the JDesktop (jdic) parser (using your standard browser as parser)...
    The problem I have :
    I have a "JTabbedPane" containing a "JSpitPane". This JSplitPane contains a "JCombobox" (as URL field) and a "JScrollPane".
    The "JScrollPane" contains the jdic WebBrowser...
    When I resize the JFrame of my application bigger, everything will resize okay. When I'm making my JFrame smaller, the JScrollPane doesn't resize correctly , so the scrollbars are gone !
    I tried already a lot of things like putting the jdic WebBrowser directly in the JSplitPane, using a JPanel instead of the JSplitPane, ...
    It only works correctly if I add the jdic Webbrowser directly to the JTabbedPane...
    I know it's difficult to understand but I hope somebody can help me !
    If you know another solution to add a JCombobox and a jdic Webbrowser together, let me know !"
    Thx in advance!
    grtz
    Unzip

    Hi,
    The JPanels which you have inside each tab of the JTabbedPanes should have BorderLayout and the JScrollPanes which hold the JTables should be added with the BorderLayout.CENTER constraint. This will make sure that the JScrollPanes that contain the JTables occupy as much space as possible.
    Hope this helps,
    Ranga.

  • JTable in JScrollPane auto resize refresh problem

    Hello,
    I have a JTable in a JScrollPane. Number of rows is changing.
    I'm using the following to auto-resize JScrollPane.
    public Dimension getPreferredSize() {
                  Dimension size = super.getPreferredSize();
                  size.height -= getViewport().getPreferredSize().height;
                  Component view = getViewport().getView();
                  if(view != null)
                  size.height += view.getPreferredSize().height;
                  return size;
             }There is a JButton, which adds an empty row to the JTable. It all works fine, except the auto-resize when a new row is added. I want all rows of JTable to be visible, with no scrollbars present. I tried repaint(), revalidate(), addNotify(). What should I do?
    Thanks.

    Sure
    DefaultTableModel dtm = new DefaultTableModel(vec, header);
              jt0 = new JTable(dtm);
              jt0.getTableHeader().setReorderingAllowed(false);
              jt0.setFont(new Font("Tahoma", Font.PLAIN, 12));
              jt0.getTableHeader().setFont(new java.awt.Font("Tahoma", java.awt.Font.BOLD, 12));
              jt0.setRowHeight(18);
            jt0.setPreferredScrollableViewportSize(new Dimension(500, jt0.getRowCount() * jt0.getRowHeight()));
            jt0.setFillsViewportHeight(false);
              jsp0 = new JScrollPane(jt0);
    GridBagConstraints gbc = new GridBagConstraints(); 
            gbc.insets = new Insets(2,1,2,1); 
            gbc.weightx = 1.0; 
            gbc.weighty = 1.0; 
            JPanel p0 = new JPanel(new GridBagLayout()); 
            gbc.fill = gbc.HORIZONTAL;
            p0.add(jsp0, gbc);
              JButton jb1 = new JButton("add row");
              jb1.setSize(40, 18);
    jb1.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {
                        dtm.addRow(new Object[]{....});
    //                    jt0.scrollRectToVisible(jt0.getCellRect(jt0.getModel().getRowCount()-1, 1, false));
    //                    jt0.setRowSelectionInterval(jt0.getModel().getRowCount()-1, jt0.getModel().getRowCount()-1);
        public class SizeX extends JScrollPane {
             public Dimension getPreferredSize() {
                  Dimension size = super.getPreferredSize();
                  size.height -= getViewport().getPreferredSize().height;
                  Component view = getViewport().getView();
                  if(view != null)
                  size.height += view.getPreferredSize().height;
                  return size;
        }

  • JTree in JScrollPane not resizing after model change.

    I have a JTree in a JScrollPane that's put in a JPanel using the JGoodies FormLayout as it's layout manager. The column definition defines the column to grow so the JScrollPane should have enough space. The tree is empty when I create it and put it in the JScrollPane.
    After adding some nodes to the tree the JScrollPane does not resize automatically, it only resizes when a forced repaint occurs (moving or resizing the window , etc).
    I've tried calling invalidate(), repaint(),revalidate() on both the JTree and the JScrollPane. I also do a reload() on the TreeModel after adding the nodes (which is probably unnecessary as I use insertNodeInto(node,parent,position) from the DefaultTreeModel to add the new nodes).
    Anybody knows what I'm missing here?
    Thanks a lot in advance !

    Update:
    The card is running now. I had another Arch system (arch2) on the same network (to compare with), and after I shut that down and rebooted the first one (arch1) the network interfaces show up, both lo and eth0.
    However, the startup routine hangs about 2-3 minutes on the network daemon (with blinking router lights and hdd activity), so it's still not perfect. Another thing is that I can't get the right gateway from the router's dhcp. Here's an overview of the setup:
    Home: 192.168.2.x
    arch1 .2.102-------|
    |
    arch2 .2.101-------| old SMC router: .2.1
    |
    fritzbox .2.2 -----|
    router/modem
    |
    |
    ~~~~~
    internet
    The gateway is supposed to be the fritzbox with ip 192.168.2.2. The old SMC router serves addresses in the range .2.101-110. I set it up this way because I need the 8 ports on the SMC (and I like watching the lights).
    Here's my /etc/rc.conf for both systems:
    arch1 (starts slow):
    eth0="dhcp"
    ROUTES=(!gateway)
    arch2 (working):
    eth0="eth0 192.168.2.101 netmask 255.255.255.0 broadcast 192.168.2.255"
    gateway="default gw 192.168.2.2"
    ROUTES=(gateway)
    arch1 gets the SMC as gateway, arch2 gets the fritzbox.
    Ideally all computers on the network should get their IPs from the SMC dhcp, which also gives them the fritzbox as gateway. But that just doesn't work for the arch1. arch2 and the windows PCs get online just fine.
    I had also tried setting arch1 the same as arch2 except for the ip=2.102. Then the network starts faster, but the gateway is still stuck at the SMC router -> no internet.
    Rather complicated, but what are networks for? Anyone see daylight in this mess?
    Last edited by bitpal (2009-08-13 21:24:02)

  • JScrollPane image resizing

    Hi, i've a JScrollPane into my class "Scroll image" I want that the imageicon automatically is resized when i move the border of JscrollPane, i do not suceed to do this. help me.
    <code>
    * scroll_image.java
    * Created on 31 maggio 2004, 13.26
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.geom.*;
    public class scroll_image extends JPanel implements ChangeListener{
    JScrollPane si;
    int max_w = 300 ;
    int max_h = 300;
    ImageIcon def;
    JLabel et;
    ImageIcon tmp;
    BorderLayout lay = new BorderLayout();
    public scroll_image(BufferedImage buf) {
    this.setLayout(lay);
    tmp = new ImageIcon(buf);
    Image im = tmp.getImage();
    Dimension d = getScaledSize(tmp);
    def = new ImageIcon (im.getScaledInstance(d.width, d.height, Image.SCALE_SMOOTH) ) ;
    et = new JLabel(def);
    et.setBounds(0, 0, d.width, d.height);
    si = new JScrollPane(et);
    si.revalidate();
    si.setVisible(true);
    add (BorderLayout.CENTER, si);
    this.revalidate();
    this.setVisible(true);
    private Dimension getScaledSize(ImageIcon image) {
    double imageRatio =
    (double)image.getIconWidth() / (double)image.getIconHeight();
    if ( imageRatio > 1.0)
    return new Dimension( max_w,(int)(((double)max_h)/imageRatio) );
    else
    return new Dimension( (int)(((double)max_w)*imageRatio), max_h );
    public scroll_image get_scroll_image (){
    return this;
    public void paintComponent (Graphics g){
    setOpaque(false);
    revalidate();
    Dimension ddd = this.getSize();
    g.drawImage(def.getImage(), 0, 0, ddd.width, ddd.height, null);
    public void stateChanged(javax.swing.event.ChangeEvent ae) {
    revalidate();
    paintComponent(getGraphics());
    </code>
    How many errors i've done? where?
    Thank you.

    That was a joke referring to the fact that you posted the same message many times.
    I don't understand your requirements for a JScrollPane, but here is a resizable icon:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ResizableImageIcon implements Icon {
        private BufferedImage original, latest;
        public ResizableImageIcon(BufferedImage original, JLabel label) {
            if (original == null)
                throw new NullPointerException();
            this.original = this.latest = original;
            setIconFor(label);
        //ICON METHODS
        public int getIconWidth() {
            return latest.getWidth();
        public int getIconHeight() {
            return latest.getHeight();
        public void paintIcon(Component c, Graphics g, int x, int y) {
            AffineTransform xform = AffineTransform.getTranslateInstance(x,y);
            ((Graphics2D)g).drawRenderedImage(latest, xform);
        //CLASS METHODS
        public void setMaxSize(int w, int h) {
            if (w == getIconWidth() && h == getIconHeight())
                return;
            double factor = Math.min(w/(double)original.getWidth(), h/(double)original.getHeight());
            latest = ImageUtilities.getScaledInstance(original, factor, null);
        private void setIconFor(JLabel label) {
            label.setIcon(this);
            label.addComponentListener(new ComponentAdapter(){
                public void componentResized(ComponentEvent e) {
                    JLabel l = (JLabel) e.getComponent();
                    Insets insets = l.getInsets();
                    int w = l.getWidth() - insets.left - insets.right;
                    int h = l.getHeight() - insets.top - insets.bottom;
                    setMaxSize(w, h);
                    l.setIcon(ResizableImageIcon.this); //causes repaint?
                    l.repaint();
        //SAMPLE
        public static void main(String[] args) throws IOException {
            URL url = new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg");
            JLabel label = new JLabel((Icon)null);
            label.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
            new ResizableImageIcon(ImageIO.read(url), label);
            JFrame f = new JFrame("ResizableImageIcon");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(label);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }And here is the utility code.
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ImageUtilities {
        public static void loadImage(Image image, Component c) {
            try {
                if (image instanceof BufferedImage)
                    return; //already buffered
                MediaTracker tracker = new MediaTracker(c);
                tracker.addImage(image, 0);
                tracker.waitForID(0);
                if (MediaTracker.COMPLETE != tracker.statusID(0, false))
                    throw new IllegalStateException("image loading fails");
            } catch (InterruptedException e) {
                throw new RuntimeException("interrupted", e);
        public static ColorModel getColorModel(Image image) {
            try {
                PixelGrabber gabby = new PixelGrabber(image, 0, 0, 1, 1, false);
                if (!gabby.grabPixels())
                    throw new RuntimeException("pixel grab fails");
                return gabby.getColorModel();
            } catch (InterruptedException e) {
                throw new RuntimeException("interrupted", e);
        public static BufferedImage toBufferedImage(Image image, GraphicsConfiguration gc) {
            if (image instanceof BufferedImage)
                return (BufferedImage) image;
            loadImage(image, new Label());
            ColorModel cm = getColorModel(image);
            int transparency = cm.getTransparency();
            int w = image.getWidth(null);
            int h = image.getHeight(null);
            if (gc == null)
                gc = getDefaultConfiguration();
            BufferedImage result = gc.createCompatibleImage(w, h, transparency);
            Graphics2D g = result.createGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();
            return result;
        public static GraphicsConfiguration getDefaultConfiguration() {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gd = ge.getDefaultScreenDevice();
            return gd.getDefaultConfiguration();
        public static BufferedImage copy(BufferedImage source, BufferedImage target, Object interpolationHint) {
            Graphics2D g = target.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolationHint);
            double scalex = (double) target.getWidth() / source.getWidth();
            double scaley = (double) target.getHeight() / source.getHeight();
            AffineTransform at = AffineTransform.getScaleInstance(scalex, scaley);
            g.drawRenderedImage(source, at);
            g.dispose();
            return target;
        public static BufferedImage getScaledInstance2D(BufferedImage source, double factor, Object interpolationHint, GraphicsConfiguration gc) {
            if (gc == null)
                gc = getDefaultConfiguration();
            int w = (int) (source.getWidth() * factor);
            int h = (int) (source.getHeight() * factor);
            int transparency = source.getColorModel().getTransparency();
            return copy(source, gc.createCompatibleImage(w, h, transparency), interpolationHint);
        public static Image getScaledInstanceAWT(BufferedImage source, double factor, int hint) {
            int w = (int) (source.getWidth() * factor);
            int h = (int) (source.getHeight() * factor);
            return source.getScaledInstance(w, h, hint);
        //best of breed
        public static BufferedImage getScaledInstance(BufferedImage source, double factor, GraphicsConfiguration gc) {
             if (factor >= 1.0)
                 return getScaledInstance2D(source, factor, RenderingHints.VALUE_INTERPOLATION_BICUBIC, gc);
             else {
                 Image image = getScaledInstanceAWT(source, factor, Image.SCALE_AREA_AVERAGING);
                 return toBufferedImage(image, gc);
    }

  • JSplitPane JTabbedPane Canvas resize problem

    I am using a JSplitPane to separate a tree and a JTabbedPane containing java.awt.Canvas based objects.
    I have not been able to find a way to resize the split plane over the tabbed pane. I pretty sure this
    is because the Canvas is heavyweight and the split pane lightweight, but I cannot swap out the canvas
    for a JPanel (or other swing equivalent) due to performance requirements. Is there a way to allow the
    split pane to resize over the heavyweight object?
    Below is a code snippet which illustrates what I'm trying to do. Any help would be greatly appreciated.
    Thanks!
    import javax.swing.*;
    import java.awt.*;
    public class TabTest
    public static void main(String args[])
    JFrame f = new JFrame("TabTest");
    f.setSize(800,800);
    JTree left = new JTree();
    JTabbedPane right = new JTabbedPane();
    Canvas canvas = new Canvas();
    right.add("Canvas", canvas);
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, right);
    f.getContentPane().add(splitPane);
    f.show();
    }

    I am using gl4java's GLAnimCanvas as the canvas based object in my application. Since
    the Swing based gl4java object is not hardware accellerated, it is way to too slow for my application
    (a 3D gui ).

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

  • Getting JScrollPane to resize with container...

    I am tearing my hair out trying to get a JScrollPane containing a JTree to properly resize when its parent container is resized (and indeed to be sized properly when first added to the container).
    Currently, the scrollpane sizes itself to its child (tree), which is much larger than the preferred size of the containing JPanel. consequently no scrollbars are shown, and the tree is centered in the display.
    Any help greatly appreciated!
    A minimal example of code that behaves badly in this respect follows:
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //ScrollTest.java
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.awt.event.WindowAdapter;
    public class ScrollTest{
    public static void main(String[] args){
    DefaultMutableTreeNode top = new DefaultMutableTreeNode("TEST");
    DefaultMutableTreeNode curNode = top;
    JTree jt = new JTree(top);
    StringBuffer sb = new StringBuffer("TEST:");
    for (int i=0;i<10;i++){
    DefaultMutableTreeNode n = new DefaultMutableTreeNode(sb.toString());
    curNode.add(n);
    curNode = n;
    sb.append(sb.toString());
    jt.expandRow(i);
    JScrollPane jsp = new JScrollPane(jt);
    JPanel jp = new JPanel();
    jp.setPreferredSize(new Dimension(200,200));
    jp.add(jsp,BorderLayout.CENTER);
    JFrame jf = new JFrame("Test");
    jf.setContentPane(jp);
    jf.addWindowListener(new WindowAdapter(){
    public void windowClosing(){
    System.exit(0);
    jf.pack();
    jf.show();
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    ok: don't set the the content pane.
    add the JPanel to the content pane: getContentPane.add(jp, BorderLayout.CENTER);
    (the content pane of a JFrame has a BorderLayout by default), that way your scroll pane should resize automatically when and if you resize the JFrame.
    thomas

  • JScrollPane, JList, Resizing - How does it work?

    Hello NG,
    I have the following situation:
    3 JScrollpanes with 3 JLists to display. 2 Scrollpanes (on the right, 2. and 3.) are in a JPanel with GridBagLayout. This JPanel and the 3rd JScrollpane (on the left, 1.) are in another JPanel also with GridBagLayout. All components have a gridBagConstraints.fill = BOTH setting for resizing. The JLists will be filled from another Thread different from the EventDispatcherThread.
    The Problem:
    The JFrame with the components above will be displayed on the screen. Then the other thread fills the JList of JScrollpane(1), then the two other JScrollpanes (2 and 3). After that, a resizing occurs according to the gridBagConstraints.fill constraint to fill the space between the components. So, the 3 JScrollpanes change their size, it seem to the observer that this resizing occurs without intention.
    Is there a way to prevent this risizing? How does this resizing mechanism exactly works? Who fires which event? Does anybody knows where to find a good description of it?
    So far, I know it starts with the revalidate()-method in the JLists after changing the content of the lists. revalidate() adds the component to the RepaintManger invalidation queue for repainting. But who calls revalidate()? What will happen if the revalidate()-method will be overwritten to do nothing?
    Bye
    Raoul

    You gotta throw use a bone here... How does what work? More info please.

  • Canvas3D within JSplitPane - can't resize

    I am trying to put a Canvas3D (which is first placed into a JPanel) within a JSplitPane to create some CAD-style editor. The problem is, that you can only make the Canvas3D bigger using the JSplitPane's separator, there seems to be no way to reduce its size again.
    I have searched the forum and found some people having the same problem, but no one found a solution yet.
    Does anyone know a way how to fix this?

    Hi,
    I seem to have the same problem. I tried overriding these methods in the extended Canvas3D class but still the Canvas3D resizes on its own during rendering and flickers. Is there any way to completely constrain the resizing of the Canvas3D?
    Thanks,
    Raghav
    Okay, it seems to be a known problem, and I found a
    simple rework. Overriding the getPreferredSize and
    getMinimumSize methods to return (0,0) will do the
    job.
    Still looking for sideeffects, though.

  • Nested JPanel resizing

    In one of my application there is one Jframe( BorderLayout) containing panel at the center surrounded with JScrollPane. The panel contains one more JPanel in it.
    On click of a button i need to resize both the panel.
    in the event handler method, Im caling setPreferedSize() and setSize() for both the panels.
    Only outer panel gets resized for the first click and for the second click inner panel gets resized...
    how can i solve this problem...?

    There is no way of knowing where the problem is without the code, however, you said you have called the setPreferedSize() and setSize() methods in the event handler.
    This should get called when you press the button, one thing you must do is to make sure that they are both inside the same block of code. If you are using an if statement.
    if(buttonPressed()){
    setPreferedSize();
    setSize();
    }Or you could post a simple version to help us solve the problem.

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

  • Dynamic JPanel resizing?

    Hey all,
    I'm displaying an image in a JPanel and I want the user to be able to resize the panel by dragging with the mouse as you would say in Photoshop. Obviously the image should resize to fill the panel as it's enlarged (showing resizing handles on the image/panel would also be good).
    For bonus points:
    I also have a draggable method so the image can be moved on the screen, the resizing method should only be applied when the mouse is over the edges of the image/panel.
    Thanks for your suggestions.

    For bonus points:
    I also have a draggable method so the image can be moved on Ooh bonus points! Now ur talking
    Search google for my Resizeable.java class. This should take care of resizing. As far as scaling the image, that call all be done in the paintComponent method. But actually I've got a class for this too
    You are welcome to use and modify this class, but please don't change the package or take credit for it as your own work (except where you have modified it)
    ExpandableImagePanel.java
    ======================
    package tjacobs.ui.ex;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.LayoutManager;
    import java.awt.Toolkit;
    import javax.swing.JPanel;
    import tjacobs.ui.fc.FileExtensionFilter;
    import tjacobs.ui.swing_ex.JFileChooser;
    import tjacobs.ui.util.WindowUtilities;
    * @deprecated use BackgroundImagePanel
    * @see BackgroundImagePanel
    * @author HP_Administrator
    public class ExpandableImagePanel extends JPanel {
         private static final long serialVersionUID = 1L;
         Image mOriginal;
         public ExpandableImagePanel() {
         public ExpandableImagePanel(Image im) {
              this();
              setImage(im);
         public ExpandableImagePanel(LayoutManager arg0) {
              super(arg0);
         public ExpandableImagePanel(boolean arg0) {
              super(arg0);
         public ExpandableImagePanel(LayoutManager arg0, boolean arg1) {
              super(arg0, arg1);
         public void setImage(Image im) {
              mOriginal = im;
         public Image getImage() {
              return mOriginal;
         public void paintComponent(Graphics g) {
              //super.paintComponent(g);
              g.clearRect(0, 0, getWidth(), getHeight());
              g.drawImage(mOriginal, 0, 0, getWidth(), getHeight(), null);
         public static void main(String[] args) {
              JFileChooser chooser = new JFileChooser();
              chooser.addChoosableFileFilter(new FileExtensionFilter.ImageFilter());
              int approve = chooser.showOpenDialog(null);
              if (approve == javax.swing.JFileChooser.APPROVE_OPTION) {
                   //BufferedImage im = new BufferedImage(chooser.getSelectedFile());
                   Image im = Toolkit.getDefaultToolkit().createImage(chooser.getSelectedFile().getAbsolutePath());
                   ExpandableImagePanel p = new ExpandableImagePanel(im);
                   p.setPreferredSize(new Dimension(300,300));
                   WindowUtilities.visualize(p);
    }

Maybe you are looking for

  • Adobe Acrobat - Digital Signatures Security

    Hi, The business I am working for is making a push for online fill in forms for simplicity and less paperwork. At the moment they are using word docs with fill in sections that are terrible to deal with and still require you to print them out to sign

  • Connection problems after updating to iOS 5

    Hello everyone, I updated my iPhone 4 (bought it in June '10) to iOS5 a week ago like everyone else. Ever since then, I've been experiencing problems with pretty much anything that requires a data connection. It won't send messages, log in to Faceboo

  • Transports(bps objs)

    Hi mates, Base cube(bw) is linked to Plnning cube(sem) via DTP & transformation and everyday data is to be updated in plnning cube. I have to design one process chain for this requirement which should be triggered at particular time. Base cube is alr

  • How do I show Safari webpage from my apple computer to appletv

    I just bought apple tv and am trying to display the safari webpage from my MacBook onto the apple tv monitor.  I tried selecting the airplay in my itunes account but that doesn't seem to help with Safari.  Any advise?  Thanks

  • Help..how to make right click on jtable pleassssssss

    I'm creating a table that need to have a right click on the row please help me I really need this in my project....