Size of ScrollPane (JViewport)

I have a JScrollPane that contains a JTextArea.
When I write more text to the text area the scroll bar appears and that's fine.
But if I pack() the window the text area gets bigger so that all the text is visible and that's my problem.
What can I do?
I tryed setting the size of the JViewport but it didn't work...

Don't pack() then, it will attempt to resize the components "optimally" which is obiviously not what you're wanting.

Similar Messages

  • How can I know the size of a JViewport laid out in BorderLayout.CENTER?

    I have a JPanel inside a JScrollPane. The scroll pane is laid out inside of BorderLayout.CENTER. I need to know the size of the JViewport to do stuff like centering and zooming.
    Where can I find the size? All these methods return 0 values for X and Y:
    myScrollPane.getViewport().getSize()
    myScrollPane().getSize()
    myScrollPane.getHorizontalScrollbar().getValue()
    Yes, even the scrollbars won't give me any values! It's all because of the BorderLayout!
    Any ideas? Thanks.

    Sounds like you are accessing the sizes before the views are realized (that is before a call to frame.pack()/show()) They are available only after the layoutManager had a go on it. What is available earlier are preferred/min/max, though.
    Greetings
    Jeanette

  • How do I create an infinite drawing canvas in a ScrollPane?

    I wanted to figure this out on my own, but it is time to ask for help. I've tried too many different things. The closest I've come to the behaviour I want is with this code:
    final BorderPane root = new BorderPane();
    final Pane canvasWrapper = new Pane();
    canvasWrapper.setPrefSize(800, 500);
    canvasWrapper.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
    canvasWrapper.setStyle("-fx-background-color: lightgray; -fx-border-color: green; -fx-border-width: 2px;");
    final Group canvas = new Group();
    canvasWrapper.getChildren().add(canvas);
    final ScrollPane scroll = new ScrollPane();
    scroll.setContent(canvasWrapper);
    root.setCenter(scroll);
    // event code for adding circles and lines to the canvas
    I want the ScrollPane to be filled with the Pane, so it can catch events for drawing. When the stage is resized, the ScrollPane is resized too. This the result of the BorderPane. What I want is to expand the window and have canvasWrapper expand to fill the entire ScrollPane viewport. When the stage is made smaller the ScrollPane shrinks, but I want the canvasWrapper to retain its size. The idea is the drawing canvas can only grow. When it gets too large for the current stage/ScrollPane size, the scrollpane can be used to navigate around the canvas.
    I tried using
    scroll.setFitToHeight(true);
    scroll.setFitToWidth(true);
    but this causes the Pane to be made smaller when the viewport is made smaller.

    I figured it out!
    Use
    scroll.setFitToHeight(true);
    scroll.setFitToWidth(true);
    to resize the Pane as the view port changes.
    Save the canvas' size as the Pane's size.
    canvas.layoutBoundsProperty().addListener(new ChangeListener<Bounds>() {
                @Override
                public void changed(ObservableValue<? extends Bounds> ov, Bounds t, Bounds t1) {
                    canvasWrapper.setMinSize(t1.getMaxX(), t1.getMaxY());
    This forces the Pane to always be as large as the group is.
    Missed a piece of code - jrguenther

  • Automating scrolling of a JTable when model gets updated

    Hi,
    I have a JTable in a JScrollPane with a table model that updates in real time and I need to keep the currently selected row on the same place on screen (for example when a row is inserted before the selected row I'd like the scroll pane to automatically scroll one row down so the selected row remains at the same location on screen).
    the scrollpane before the row insertion:
    row A
    row B
    row C
    row D (selected)
    row E
    now 'row F' is inserted between B and C
    row B
    row F
    row C
    row D (selected)
    row E
    (row A is scrolled out of sigth and D remains (visually) the 4th row in the view)
    Is there any easy way how to achieve this ? I tried a number of approaches but all end up with an annoying scrollpane jitter.

    I'd try to call JViewPort's scrollRectToVisible(Rectangle contentRect) for the JScrollPane.getViewPort() and keep the parameter Rectangle's size the same (JViewPort.getViewRect()) but adjust the y-position by amount returned by JTable.getRowHeight() + JTable.getRowmargin(). This would be done after row wuold be added and only if vertical scrollbar is visible.
    Maybe this is what you have tried already. Anyway I hope this helps.

  • Buggy JTabbed Pane, Scroll? Constraints?

    I don't know if this is a bug, limitation, or if I'm not implementing it properly, but I am having a problem with scroll panes in a tabbed frame.
    Here's the scoop.
    I have a JFrame which has a has a JTabbedPane north and a JPanel (which contains a couple components) down south.
    The tabbed pane has 4 tabs/panes. Only the first two are relevant right now because I haven't made it to the last two.
    Tab 1 has a JPanel with a gridlayout (2 cols, 3 rows). The components display fine until I populate tab 2 with my 25 rows of stats. Once that happens, the JFrame (the container/content pane, not the physical window) size stretches itself to about 600px tall.
    Tab 2 contains a JPanel with a gridlayout (2 cols, 25 rows). As described above, this many rows causes every pane in the tabbed pane set to take on this size, causing undesirable spacing. Not only that, you have to resize the window to display it all.
    My solution was to use a JScrollPane to contain the JPanel with all the rows, and then add the JScrollPane to the tab. This just doesn't work. The result was just a border around the JPanel, no scroll.
    Can someone give me some ideas on how to use a JScrollPane as the component in the tab 2?
    Also, how do I control the size of JPanels in the the tabbed panes so they do not change based on the size of another pane?
    Thanks So Much!!!
    Here is my constructor code (irrelvant logic not included):
    public CbStats() {
    //create main frame
    JFrame frame = new JFrame("VSN1 Callback Stats");
    frame.setSize(400,200);
    //main container
    Container content = frame.getContentPane();
    //tabbed pane goes north
    JTabbedPane tabs = new JTabbedPane();
    //flow panel goes south
    JPanel southPanel = new JPanel();
    southPanel.setLayout(new FlowLayout());
    //add status and manual refresh
    JLabel status = new JLabel("Refresh Rate: 2 mins ");
    southPanel.add(status);
    JButton manRefresh = new JButton("Manual Refresh");
    southPanel.add(manRefresh);
    //create 4 panels, 1 for each tab
    JPanel panSummary = new JPanel();
    JPanel panPerf = new JPanel();
    JPanel panNotes = new JPanel();
    JPanel panJump = new JPanel();
    //add stuff to panel 1
    panSummary.setLayout(new GridLayout(5,2));
    panSummary.add(new JLabel(" Open Tickets:"));
    panSummary.add(openTix);
    panSummary.add(new JLabel(" Assigned Tickets:"));
    panSummary.add(assignedTix);
    panSummary.add(new JLabel(" Closed Tickets:"));
    panSummary.add(closedTix);
    //add stuff to panel 2
    //panPerf.setLayout(new FlowLayout());
    panUsers.setLayout(new GridLayout(25,4));
    for(int i=0;i<ulAr.length;i++) {
    ulAr[i] = new JLabel();
    panUsers.add(ulAr);
    panPerf.add(panUsers);
    //add panels to tabs
    tabs.add(panSummary, "Summary");
    tabs.add(panPerf, "Performance");
    tabs.add(panNotes, "Notes");
    tabs.add(panJump, "Jump To...");
    //add tabbed pane to main frame
    content.add(tabs, BorderLayout.NORTH);
    content.add(southPanel, BorderLayout.SOUTH);
    //make visible
    frame.setVisible(true);

    You have to specify real panel's size.
    panel.setPrefferedSize(...);
    JScrollPane will ask the panel and if the size of panel is bigger than the size of scrollpane scrollbars appear.
    And of course you have to specify size of scroll.
    hope this helps.
    Stas

  • JDialog/JTable sizing

    I have a JDialog with a JTable/scroll pane. The JTable has headers but no data initially.
    I want to set the min size samller than the initial size.
    When I try setSize/setPreferred size this is not working. It always inits to the min size.
        public TheDialog(Frame parent)
            super(parent);
            theModel = new TheTableModel();
            theTable      = new TheTable(thetableModel);
            Dimension size = new Dimension(100,400);
            setLayout(new BorderLayout());
            JScrollPane scrollPane = new JScrollPane(theTable,
                                                     JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                                     JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            scrollPane.setPreferredSize(size);
            scrollPane.setSize(size);
            add(scrollPane, BorderLayout.CENTER);  
            setPreferredSize(size);
            setSize(size);
           setMinimumSize(new Dimension(100,20));

    I am fairly new to the forum
    Didn't know that people cared about any feedbackWhat does being new to a forum have to do with anything?
    In other words you don't believe in saying "thank you" when someone gives you help, whether in a forum or in other apects of daily life?
    Maybe the following will work:
    table.setPreferredScrollableViewportSize(...);If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • Dimension of Jtable

    Hi,
    I would use 6-7 Jtable in my panel, each table have one only row, when I use one onle table, it display correctly but although have one row the border of the table comprises nearly all panel,when I add another jtable the two Table become very small....
    why?
    exist a way for to set the height of the JTable??
    thanks
    ps. sorry for my bad english..

    In the future, Swing related questions should be posted in the Swing forum.
    Don't create your own TableModel. Just use the DefaultTableModel until you better understand how JTable works. Here is a simple working example:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=637504
    Note the following line:
    table.setPreferredScrollableViewportSize(table.getPreferredSize());which sizes the scrollpane to be the same size as the table.

  • Buggy pref pane (video included)

    Does anybody know what this is about and how to fix it?
    Click to play movie
    I'm not even sure that's what the airport pane is supposed to look like in Tiger. I'm none too keen on taking drastic measures at this point. I hope it's a simple fix. Thanks in advance!
    PowerMac G5 (June 2004) 2x1.8GHz 1.25GB, PowerBook G4 (12-inch DVI) 1x1GHz 768MB   Mac OS X (10.4.7)  

    You have to specify real panel's size.
    panel.setPrefferedSize(...);
    JScrollPane will ask the panel and if the size of panel is bigger than the size of scrollpane scrollbars appear.
    And of course you have to specify size of scroll.
    hope this helps.
    Stas

  • Using JScrollPane

    hello
    i have someproblem in using JScrollPane
    i making some applet,i put in it JScrollPane and inside it i put the the JTextPane
    each time i add new string to the text pane
    i add it in new line
    after while the last inserted string in not viewable
    i have to move the scroll pane myself to view the last statement
    i added some code after inserting the new string i do the following
    int maxYPos;
    maxYPos = ReceivedTextScrollPane.getViewport().getViewSize().height;
    ReceivedTextScrollPane.getViewport().setViewPosition(new Point ( 0, maxYPos));
    it works well for moving the scroll automatically
    but the proble happens when i implement this code while in the first added strings ,i mean at the first five added strings in the textpane ,in which the size of string is smaller than the size of scrollpane , it cause some bug that sometimes it turn the color of the textpane and scroll to gray color and hide the text in it.
    please if any one could help
    i will apperciate that for him
    thanks in advance

    the easiest way to scroll the text pane is to just use
    textPane.setCaretPosition( textPane.getDocument().getLength() );

  • Signal function on complete of another function

    Argh.. This seems pretty easy but I cannot find information about this anywhere.  I might just be searching wrong..
    Anyway, I'd like to signal a function to run when another function completes.
    I am filling a scrollPane with some dynamic content and want it to resize once the content has filled in some dynamic text boxes.
    I'd like to signal a resize function once the function that fills in the scrollPane completes.  I tried something like this but it does not seem I can add this sort of listener to a funciton.
    scrollPanePopulate.addEventListener(Event.COMPLETE, scrollPaneResize);
    I might be missing something obvious or just be headed down the wrong path.  Thanks in advance..
    -j

    function scrollPanePopulate(event:Event):void{
    //show scroll pane
         scrollPane.visible=true;
    //create the temp variables
         var calledMarkerIndex=pntxml.row[pointindex].ID;
         var calledMarkerDate=pntxml.row[pointindex].DATE;
         var calledMarkerDescription=pntxml.row[pointindex].DESC;
         var calledMarkerContent=pntxml.row[pointindex].URL_OF_CONTENT;
         var imgSource:String = "<img src="+"'"+calledMarkerContent+"'"+"width='405'"+"height='280'"+"/>";
    //fill in the text
         scrollPaneContent.scrollPaneImage.htmlText=imgSource;
         scrollPaneContent.scrollPaneText.htmlText="<font size='12' color='#ffffff'>"+calledMarkerDescription;
         scrollPane.update();
         scrollPane.verticalScrollPosition=(0);
    and something like this would size my scrollPane to a reasonable size
    function scrollPaneResize(event:Event):void{
    //resize the scrollpane to content's size
         var imgHeight=scrollPaneContent.scrollPaneImage.height;
         var txtHeight=scrollPaneContent.scrollPaneText.height;
         var contentHeight=(imgHeight+txtHeight);
         scrollPane.setSize(510,(contentHeight+50));
    Finally..  What I'll ultimatley do is set this up so that if the two componenent in my scrollPane are too large (height+height) then I'll have a maximum size that the scrollPane can attain

  • JLabel Editing

    For the past few days I have been struggling with creating a GUI for a program I am developing with the aim of extracting index.dat files. The user selects the file they wish to analyse, the program outputs various details to the interface. However, I am having issues trying to implement this with the JLabel 'size'. Others such as the JTextAreas have not yet been attempted.
    The program itself runs fine in the background however, none of the details are added to the interface itself.
    The following is the code I have so far for implementing the GUI, apologise if this seems messy, however I have been editing it quite abit recently trying to solve the issue. Not all aspects of this program have been implemented yet, such as methods for editing the JTextAreas, as I am currently just trying to solve the setIndexInfo() method when editing the 'size' JLabel.
    public class GUInterface extends JFrame implements ActionListener
        //creating GUI variables
        JMenuBar menuBar;
        JMenu file;
        JMenuItem historyItem, flashItem, exit;
        JFileChooser filechoose;
        JPanel info, top, output, cacheDisplay;
        JTextArea cache, display;
        JLabel type, loc, size;
        JScrollPane scrollpane;
        File f = new File("C:\\");
        String locStr;
        public void create()
            guInterface();
        }//end create
        public void guInterface()
            //initialising variables
            menuBar = new JMenuBar();
            file = new JMenu("File");
            historyItem = new JMenuItem("Index.dat");
            flashItem = new JMenuItem("Flash Cookies");
            exit = new JMenuItem("Exit");
            filechoose = new JFileChooser();
            info = new JPanel();
            top = new JPanel();
            cacheDisplay = new JPanel();
            cache = new JTextArea(9, 10);
            type = new JLabel("AnalysisType");
            loc = new JLabel("FileLoc");
            size = new JLabel("Size");
            //creating menu bar
            menuBar.add(file);
            file.add(historyItem);
            file.add(flashItem);
            file.addSeparator();
            file.add(exit);
            //info
            info.setLayout(new BoxLayout(info, BoxLayout.Y_AXIS));
            type.setFont(new Font("Serif", Font.BOLD, 30));
            info.add(type);
            info.add(Box.createRigidArea(new Dimension(0,5)));
            loc.setFont(new Font("Serif", Font.BOLD, 20));
            info.add(loc);
            info.add(Box.createRigidArea(new Dimension(0,5)));
            size.setFont(new Font("Serif", Font.BOLD, 20));
            info.add(size);
            //cacheDisplay
            cacheDisplay.add(cache);
            cache.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            cache.setMaximumSize(new Dimension(200, 200));
            cache.setLineWrap(true);
            cache.setEditable(false);
            cache.setSize(200,100);
            //top panel
            top.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            top.setLayout(new BoxLayout(top, BoxLayout.X_AXIS));
            top.add(info);
            top.add(Box.createHorizontalGlue());
            top.add(cache);
            filechoose.setCurrentDirectory(f);
            historyItem.addActionListener(this);
            flashItem.addActionListener(this);
            exit.addActionListener(this);
            setJMenuBar(menuBar);
            //JFrame layout
            setLayout(new BorderLayout());
            add(top, BorderLayout.NORTH);
            //creating main area
            setSize(1000, 600);
            setLocationRelativeTo(null);
            setTitle("PrivateBrowse - Private Browsing Recovery Tool");
            setResizable(false);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
        }//end guInterface
        public void setIndexInfo(String output)
            size = new JLabel(output);
            size.setFont(new Font("Serif", Font.BOLD, 20));
        }//end setIndexInfo
        public void actionPerformed(ActionEvent evt)
            if(evt.getSource() == historyItem)
                 filechoose.setDialogTitle("Select index.dat");
                 filechoose.setFileSelectionMode(JFileChooser.FILES_ONLY);
                 if(filechoose.showOpenDialog(null) == filechoose.APPROVE_OPTION)
                     type.setText("Index.DAT Analysis");
                     locStr = filechoose.getSelectedFile().toString();
                     loc.setText(locStr);
                     try
                       IndexRecovery idxRcvy = new IndexRecovery();
                       idxRcvy.readFile(locStr);
                     catch(Exception e)
                         System.out.println("Error: " + e);
            else if(evt.getSource() == flashItem)
                filechoose.setDialogTitle("Select #SharedObjects Directory");
                filechoose.setApproveButtonText("Select");
                filechoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                if(filechoose.showOpenDialog(null) == filechoose.APPROVE_OPTION)
                    type.setText("Flash Cookie Analysis");
                    locStr = filechoose.getSelectedFile().toString();
                    loc.setText(locStr);
                    try
                        FlashRecovery flshRcvy = new FlashRecovery();
                        flshRcvy.extractFlash(locStr);
                    catch(Exception e)
                        System.out.println("Error: " + e);
            else if(evt.getSource() == exit)
                setVisible(false);
                dispose();
                System.exit(0);
        }//end actionPerformed
    }The class IndexRecovery calls setIndexInfo() with the size wanted to be displayed in the JLable 'size'.
    I have been looking around and heard of various functions such as repaint() and validate(), however have no clue how to use these should these be the solution.
    Any advice on the matter will be greatly appreciated.
    Thanks,
    David.

        public void setIndexInfo(String output)
            size.setText(output);
        }//end setIndexInfoOr this, to be thread safe:
    public void setIndexInfo(final String output) {
        if (SwingUtilities.isEventDispatchThread()) {
            size.setText(output);
        } else {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    setIndexInfo(output);
    }//end setIndexInfoEdited by: Andre_Uhres on Apr 6, 2010 4:58 PM

  • Problem with ScrollPane and JFrame Size

    Hi,
    The code is workin but after change the size of frame it works CORRECTLY.Please help me why this frame is small an scrollpane doesn't show at the beginning.
    Here is the code:
    import java.awt.*;
    public class canvasExp extends Canvas
         private static final long serialVersionUID = 1L;
         ImageLoader map=new ImageLoader();
        Image img = map.GetImg();
        int h, w;               // the height and width of this canvas
         public void update(Graphics g)
            paint(g);
        public void paint(Graphics g)
                if(img != null)
                     h = getSize().height;
                     System.out.println("h:"+h);
                      w = getSize().width;
                      System.out.println("w:"+w);
                      g.drawRect(0,0, w-1, h-1);     // Draw border
                  //  System.out.println("Size= "+this.getSize());
                     g.drawImage(img, 0,0,this.getWidth(),this.getHeight(), this);
                    int width = img.getWidth(this);
                    //System.out.println("W: "+width);
                    int height = img.getHeight(this);
                    //System.out.println("H: "+height);
                    if(width != -1 && width != getWidth())
                        setSize(width, getHeight());
                    if(height != -1 && height != getHeight())
                        setSize(getWidth(), height);
    }I create frame here...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class frame extends JFrame implements MouseMotionListener,MouseListener
         private static final long serialVersionUID = 1L;
        private ScrollPane scrollPane;
        private int dragStartX;
        private int dragStartY;
        private int lastX;
        private int lastY;
        int cordX;
        int cordY;
        canvasExp canvas;
        public frame()
            super("test");
            canvas = new canvasExp();
            canvas.addMouseListener(this);
            canvas.addMouseMotionListener(this);
            scrollPane = new ScrollPane();
            scrollPane.setEnabled(true);
            scrollPane.add(canvas);
            add(scrollPane);
            setSize(300,300);
            pack();
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void mousePressed(MouseEvent e)
            dragStartX = e.getX();
            dragStartY = e.getY();
            lastX = getX();
            lastY = getY();
        public void mouseReleased(MouseEvent mouseevent)
        public void mouseClicked(MouseEvent e)
            cordX = e.getX();
            cordY = e.getY();
            System.out.println((new StringBuilder()).append(cordX).append(",").append(cordY).toString());
        public void mouseEntered(MouseEvent mouseevent)
        public void mouseExited(MouseEvent mouseevent)
        public void mouseMoved(MouseEvent mouseevent)
        public void mouseDragged(MouseEvent e)
            if(e.getX() != lastX || e.getY() != lastY)
                Point p = scrollPane.getScrollPosition();
                p.translate(dragStartX - e.getX(), dragStartY - e.getY());
                scrollPane.setScrollPosition(p);
    }...and call here
    public class main {
         public main(){}
         public static void main (String args[])
             frame f = new frame();
    }There is something I couldn't see here.By the way ImageLoader is workin I get the image.
    Thank you for your help,please answer me....

    I'm not going to even attempt to resolve the problem posted. There are other problems with your code that should take priority.
    -- class names by convention start with a capital letter.
    -- don't use the name of a common class from the standard API for your custom class, not even with a difference of case. It'll come back to bite you.
    -- don't mix awt and Swing components in the same GUI. Change your class that extends Canvas to extend JPanel instead, and override paintComponent(...) instead of paint(...).
    -- launch your GUI on the EDT by wrapping it in a SwingUtilities.invokeLater or EventQueue.invokeLater.
    -- calling setSize(...) followed by pack() is meaningless. Use one or the other.
    -- That's not the correct way to display a component in a scroll pane.
    Ah, well, and the problem is that when you call pack(), it retrieves the preferredSize of the components in the JFrame, and you haven't set a preferredSize for the scroll pane.
    Please, for your own good, take a break from whatever it is you're working on and go through The Java&#8482; Tutorials: [Creating a GUI with JFC/Swing|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]
    db

  • How to restrict the maximum size of a java.awt.ScrollPane

    Dear all,
    I would like to implement a scroll pane which is resizable, but not to a size exceeding the maximum size of the java.awt.Canvas that it contains.
    I've sort of managed to do this by writing a subclass of java.awt.ScrollPane which implements java.awt.event.ComponentListener and has a componentResized method that checks whether the ScrollPane's viewport width (height) exceeds the content's preferred size, and if so, resizes the pane appropriately (see code below).
    It seems to me, however, that there ought to be a simpler way to achieve this.
    One slightly weird thing is that when the downsizing of the pane happens, the content can once be moved to the left by sliding the horizontal scrollbar, but not by clicking on the arrows. This causes one column of gray pixels to disappear and the rightmost column of the content to appear; subsequent actions on the scrollbar does not have any further effect. Likewise, the vertical scrollbar can also be moved up once.
    Also, I would like a java.awt.Frame containing such a restrictedly resizable scrollpane, such that the Frame cannot be resized by the user such that its inside is larger than the maximum size of the scrollpane. The difficulty I encountered with that is that setSize on a Frame appears to set the size of the window including the decorations provided by the window manager (fvwm2, if that matters), and I haven't been able to find anything similar to getViewportSize, which would let me find out the size of the area inside the Frame which is available for the scrollpane which the frame contains.
    Thanks in advance for hints and advice.
    Here's the code of the componentResized method:
      public void componentResized(java.awt.event.ComponentEvent e)
        java.awt.Dimension contentSize = this.content.getPreferredSize();
        this.content.setSize(contentSize);
        java.awt.Dimension viewportSize = getViewportSize();
        System.err.println("MaxSizeScrollPane: contentSize = " + contentSize);
        System.err.println("MaxSizeScrollPane: viewportSize = " + viewportSize);
        int dx = Math.max(0, (int) (viewportSize.getWidth() - contentSize.getWidth()));
        int dy = Math.max(0, (int) (viewportSize.getHeight() - contentSize.getHeight()));
        System.err.println("MaxSizeScrollPane: dx = " + dx + ", dy = " + dy);
        if ((dx > 0) || (dy > 0))
          java.awt.Dimension currentSize = getSize();
          System.err.println("MaxSizeScrollPane: currentSize = " + currentSize);
          setSize(new java.awt.Dimension(((int) currentSize.getWidth()) - dx, ((int) currentSize.getHeight()) - dy));
        System.err.println();
      }Best regards, Jan

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    public class ScrollPaneTest
        GraphicCanvas canvas;
        CustomScrollPane scrollPane;
        private Panel getScrollPanel()
            canvas = new GraphicCanvas();
            scrollPane = new CustomScrollPane();
            scrollPane.add(canvas);
            // GridBagLayout allows scrollPane to remain at
            // its preferred size during resizing activity
            Panel panel = new Panel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            panel.add(scrollPane, gbc);
            return panel;
        private WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                System.exit(0);
        private Panel getUIPanel()
            int w = canvas.width;
            int h = canvas.height;
            int visible = 100;
            int minimum = 200;
            int maximum = 500;
            final Scrollbar
                width  = new Scrollbar(Scrollbar.HORIZONTAL, w,
                                       visible, minimum, maximum),
                height = new Scrollbar(Scrollbar.HORIZONTAL, h,
                                       visible, minimum, maximum);
            AdjustmentListener l = new AdjustmentListener()
                public void adjustmentValueChanged(AdjustmentEvent e)
                    Scrollbar scrollbar = (Scrollbar)e.getSource();
                    int value = scrollbar.getValue();
                    if(scrollbar == width)
                        canvas.setWidth(value);
                    if(scrollbar == height)
                        canvas.setHeight(value);
                    canvas.invalidate();
                    scrollPane.validate();
            width.addAdjustmentListener(l);
            height.addAdjustmentListener(l);
            Panel panel = new Panel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            addComponents(new Label("width"),  width,  panel, gbc);
            addComponents(new Label("height"), height, panel, gbc);
            gbc.anchor = GridBagConstraints.CENTER;
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc)
            gbc.anchor = GridBagConstraints.EAST;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            c.add(c2, gbc);
        public static void main(String[] args)
            ScrollPaneTest test = new ScrollPaneTest();
            Frame f = new Frame();
            f.addWindowListener(test.closer);
            f.add(test.getScrollPanel());
            f.add(test.getUIPanel(), "South");
            f.pack();
            f.setLocation(200,200);
            f.setVisible(true);
            f.addComponentListener(new FrameSizer(f));
    class GraphicCanvas extends Canvas
        int width, height;
        public GraphicCanvas()
            width = 300;
            height = 300;
        public void paint(Graphics g)
            super.paint(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int dia = Math.min(width, height)*7/8;
            g2.setPaint(Color.blue);
            g2.draw(new Rectangle2D.Double(width/16, height/16, width*7/8, height*7/8));
            g2.setPaint(Color.green.darker());
            g2.draw(new Ellipse2D.Double(width/2 - dia/2, height/2 - dia/2, dia-1, dia-1));
            g2.setPaint(Color.red);
            g2.draw(new Line2D.Double(width/16, height*15/16-1, width*15/16-1, height/16));
        public Dimension getPreferredSize()
            return new Dimension(width, height);
        public Dimension getMaximumSize()
            return getPreferredSize();
        public void setWidth(int w)
            width = w;
            repaint();
        public void setHeight(int h)
            height = h;
            repaint();
    class CustomScrollPane extends ScrollPane
        Dimension minimumSize;
        public Dimension getPreferredSize()
            Component child = getComponent(0);
            if(child != null)
                Dimension d = child.getPreferredSize();
                if(minimumSize == null)
                    minimumSize = (Dimension)d.clone();
                Insets insets = getInsets();
                d.width  += insets.left + insets.right;
                d.height += insets.top + insets.bottom;
                return d;
            return null;
        public Dimension getMinimumSize()
            return minimumSize;
        public Dimension getMaximumSize()
            Component child = getComponent(0);
            if(child != null)
                return child.getMaximumSize();
            return null;
    class FrameSizer extends ComponentAdapter
        Frame f;
        public FrameSizer(Frame f)
            this.f = f;
        public void componentResized(ComponentEvent e)
            Dimension needed = getSizeForViewport();
            Dimension size = f.getSize();
            if(size.width > needed.width || size.height > needed.height)
                f.setSize(needed);
                f.pack();
         * returns the minimum required frame size that will allow
         * the scrollPane to be displayed at its preferred size
        private Dimension getSizeForViewport()
            ScrollPane scrollPane = getScrollPane(f);
            Insets insets = f.getInsets();
            int w = scrollPane.getWidth() + insets.left + insets.right;
            int h = getHeightOfChildren() + insets.top + insets.bottom;
            return new Dimension(w, h);
        private ScrollPane getScrollPane(Container cont)
            Component[] c = cont.getComponents();
            for(int j = 0; j < c.length; j++)
                if(c[j] instanceof ScrollPane)
                    return (ScrollPane)c[j];
                if(((Container)c[j]).getComponentCount() > 0)
                    return getScrollPane((Container)c[j]);
            return null;
        private int getHeightOfChildren()
            Component[] c = f.getComponents();
            int extraHeight = 0;
            for(int j = 0; j < c.length; j++)
                int height;
                if(((Container)c[j]).getComponent(0) instanceof ScrollPane)
                    height = ((Container)c[j]).getComponent(0).getHeight();
                else
                    height = c[j].getHeight();
                extraHeight += height;
            return extraHeight;
    }

  • How can I force a specific content size in a ScrollPane? -- REPOST

    See
    http://www.seanberry.com/scrollPaneInTheAss.html
    for reference
    Have an interesting situation here. I am using a scrollpane
    to hold a
    loaded movieclip (scrollContent_mc for reference) which
    contains several
    mask/image combinations. The images within scrollContent_mc
    can be
    resized by using a scale tool. When the ScrollPane redraws,
    it uses the
    total width of scrollContent_mc which includes this resized
    image
    sitting behind a mask. The result is that the viewable size
    of
    scrollContent_mc does not change (because you are only seeing
    images
    through masks), but the total size does change since the
    images can
    extend beyond the viewable bounds of scrollContent_mc.
    Is there a way to handle this? Thanks for any help.

    sberry wrote:
    > See
    http://www.seanberry.com/scrollPaneInTheAss.html
    for reference
    >
    > Have an interesting situation here. I am using a
    scrollpane to hold a
    > loaded movieclip (scrollContent_mc for reference) which
    contains several
    > mask/image combinations. The images within
    scrollContent_mc can be
    > resized by using a scale tool. When the ScrollPane
    redraws, it uses the
    > total width of scrollContent_mc which includes this
    resized image
    > sitting behind a mask. The result is that the viewable
    size of
    > scrollContent_mc does not change (because you are only
    seeing images
    > through masks), but the total size does change since the
    images can
    > extend beyond the viewable bounds of scrollContent_mc.
    >
    > Is there a way to handle this? Thanks for any help.
    Perhaps this will help explain what the problem is...
    http://seanberry.com/cheerios/holder.html
    I have a compiled movie called cheerios.swf. It is a
    200x200px movie
    with two items... a 300x300 jpg of a bowl of cheerios with a
    200x200px
    mask sitting on top of it.
    Then, in my holder movie I load the cheerios.swf into a
    scrollpane. The
    contents of the scrollpane is determined to be 300x300px,
    hence the
    100px of white space on top and bottom.
    I want the scrollpane to only target the visible portion of
    the MC
    instead of the complete contents... any ideas?

  • How can I force a specific content size in a ScrollPane -- Repost   from actionscript group

    Haven't gotten any answers in the actionscript group, so
    maybe I will
    fair better here...
    See
    http://www.seanberry.com/scrollPaneInTheAss.html
    for reference
    Have an interesting situation here. I am using a scrollpane
    to hold a
    loaded movieclip (scrollContent_mc for reference) which
    contains several
    mask/image combinations. The images within scrollContent_mc
    can be
    resized by using a scale tool. When the ScrollPane redraws,
    it uses the
    total width of scrollContent_mc which includes this resized
    image
    sitting behind a mask. The result is that the viewable size
    of
    scrollContent_mc does not change (because you are only seeing
    images
    through masks), but the total size does change since the
    images can
    extend beyond the viewable bounds of scrollContent_mc.
    Is there a way to handle this? Thanks for any help.

    sberry wrote:
    > See
    http://www.seanberry.com/scrollPaneInTheAss.html
    for reference
    >
    > Have an interesting situation here. I am using a
    scrollpane to hold a
    > loaded movieclip (scrollContent_mc for reference) which
    contains several
    > mask/image combinations. The images within
    scrollContent_mc can be
    > resized by using a scale tool. When the ScrollPane
    redraws, it uses the
    > total width of scrollContent_mc which includes this
    resized image
    > sitting behind a mask. The result is that the viewable
    size of
    > scrollContent_mc does not change (because you are only
    seeing images
    > through masks), but the total size does change since the
    images can
    > extend beyond the viewable bounds of scrollContent_mc.
    >
    > Is there a way to handle this? Thanks for any help.
    Perhaps this will help explain what the problem is...
    http://seanberry.com/cheerios/holder.html
    I have a compiled movie called cheerios.swf. It is a
    200x200px movie
    with two items... a 300x300 jpg of a bowl of cheerios with a
    200x200px
    mask sitting on top of it.
    Then, in my holder movie I load the cheerios.swf into a
    scrollpane. The
    contents of the scrollpane is determined to be 300x300px,
    hence the
    100px of white space on top and bottom.
    I want the scrollpane to only target the visible portion of
    the MC
    instead of the complete contents... any ideas?

Maybe you are looking for

  • IPod "cannot be updated.  The current file is in use."....how to fix?!

    I have a MacBook and the iPod Nano that came with it. I also have a 4G(I think) 20GB iPod. I have both configured to my Macbook, using only certain playlists to be updated on each iPod. I don't get any problems when I connect the 20GB iPod(w/ the Fir

  • CS6 Bridge and Mini Bridge problems

    Installed CS6 and clicked on Brose in Bridge.  I get the rror messare could not complete the Brose in Bridge commmand because Photoshop was unable to find the Java Script plugin.  Also when clicking on Brose in Mini Bridge I get the message cannot co

  • Acknowledging old P.O's : retriggers Release Strategy?

    Hello, I know that when you acknowledge an old Purchase Order in the Confirmations tab, it can retrigger the Release Strategy, therefore disapproving the P.O. Does this apply also if we acknowledge a P.O line item that has the Account Assignement Cat

  • Using windows 8.1 with adobe software

    Does anyone know if CS3 mastersuites will work with windows 8.1 operating system?

  • Recent air sdk (air 4.0 beta) is still not support xxhdpi

    my application is set applicationDPI = '320'. and is working well in hdpi, xhdpi etc devices... but new devices like galaxy S4 is 1920x1080 xxhdpi. air 3.9, and this 4.0 version is not support that dpi, then my app layout is still broken. this bug is