Forcing a viewport to only scroll vertically

I've created a custom LayoutManager that extends FlowLayout. Unlike FlowLayout, this layout manager creates as many columns as it can in the bounding area and justifies the component in the columns. Unlike any of the other layout managers, the number of columns is dynamic, changing as the user stretches the component.
The problem I have occurs when the developer wraps the panel in a JScrollPane. At this point, the manel inside the scroll pane has no bounded fixed size. The scrollpane basically allows the panel to be any size and it will scroll the contents appropriately. I would like the scroll pane to use the panel's preferred width and scroll the contents only in the vertical direction.
Can I accomplish this using only my layout manager, and not having to create a special JPanel class that implements the Scrollable interface or such? The attached code is my layout manager class along with a main method for testing it. Uncomment the commented line to see the problem I am having with the JScrollPane.
import javax.swing.*;
import java.awt.*;
* ColumnarFlowLayout
* @author <a href="mailto:[email protected]">James Cook</a>
public class ColumnarFlowLayout extends FlowLayout {
   // instance ----------------------------------------------------------------
   int _maxColumns = Integer.MAX_VALUE - 1;
   // constructor -------------------------------------------------------------
   public ColumnarFlowLayout() {
   public ColumnarFlowLayout(int maxColumns) {
      _maxColumns = maxColumns;
   public ColumnarFlowLayout(int hgap, int vgap) {
      super(LEFT, hgap, vgap);
   public ColumnarFlowLayout(int hgap, int vgap, int maxColumns) {
      super(LEFT, hgap, vgap);
      _maxColumns = maxColumns;
    // FlowLayout override -----------------------------------------------------
    * Lays out the container. This method lets each component take
    * its preferred size by reshaping the components in the
    * target container.
    * @param target the specified component being laid out
    * @see Container
    * @see       java.awt.Container#doLayout
   public void layoutContainer(Container target) {
      synchronized (target.getTreeLock()) {
         Insets insets = target.getInsets();
         int maxwidth = target.getWidth() - (insets.left + insets.right);
         // Stuff all of the visible components into an array
         int index = -1;
         int nmembers = target.getComponentCount();
         Component[] tempComps = new Component[nmembers];
         for (int i = 0; i < nmembers; i++) {
            Component m = target.getComponent(i);
            if (m.isVisible()) {
               index++;
               Dimension d = m.getPreferredSize();
               m.setSize(d.width, d.height);
               tempComps[index] = m;
         // Get rid of any unused component cells
         Component[] comps = new Component[index+1];
         System.arraycopy(tempComps, 0, comps, 0, comps.length);
         tempComps = null;
         // Determine the appropriate number of columns (and their widths)
         // for the given maxwidth
         int[] columnWidths = getColumnWidths(comps, maxwidth, getHgap(), _maxColumns);
         int x = 0, y = 0, maxHeight = 0;
         for (int i = 0; i < comps.length; i++) {
            Component m = comps;
int columnIndex = i % columnWidths.length;
x += (columnIndex == 0) ? 0 : columnWidths[columnIndex - 1] + getHgap();
m.setLocation(insets.left + x, insets.top + y);
maxHeight = Math.max(maxHeight, m.getHeight());
if (columnIndex == columnWidths.length - 1) {
y += maxHeight + getVgap();
x = 0;
// private -----------------------------------------------------------------
* Determine the maximum widths per column of the greatest number of
* components that will fit into a maxWidth space.
* @param comps The components to layout.
* @param maxWidth The maximum width available to layout components.
* @param hgap The horizontal space (in pixels) between components.
* @param maxColumns The maximum number of columns to use.
* @return An array that contains the widths of the resulting columns.
private int[] getColumnWidths(Component[] comps, int maxWidth, int hgap, int maxColumns) {
int[] results;
int columnCount = Math.min(comps.length + 1, maxColumns + 1);
int width = 0;
// Keep reducing the number of columns until all of the components fit
// into the allowable space. Note: The minimum number of columns will
// be one, regardless of whether it fits or not.
do {
columnCount--;
results = new int[columnCount];
for (int i = 0; i < comps.length; i++) {
int columnIndex = i % columnCount;
int componentWidth = comps[i].getSize().width;
results[columnIndex] = Math.max(results[columnIndex], componentWidth);
width = hgap * (columnCount - 1);
for (int i = 0; i < results.length; i++)
width += results[i];
} while (width > maxWidth && columnCount > 1);
return results;
// static ------------------------------------------------------------------
public static void main(String[] args) {
JFrame frame = new JFrame("ColumnarFlowLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent panel = new JPanel(new ColumnarFlowLayout(4));
String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 50; i++) {
sb.setLength(0);
for (int j = 0, c = 1 + (int)(Math.random() * 10); j < c; j++)
sb.append(s.charAt((int)(Math.random() * 26)));
panel.add(new JCheckBox(sb.toString()));
// Uncomment the following line to see the problem. A scrollpane provides the
// underlying layout manager with no limits on space. Thus, the layout manager
// isn't able to respect any boundaries.
// panel = new JScrollPane(panel);
frame.getContentPane().add(panel);
frame.pack();
frame.setSize(600,600);
frame.setVisible(true);

This may, or may not, help you. In my [url http://www.discoverteenergy.com/files/WrapLayout.java]WrapLayout class I had some success doing something similiar to what you need. It may give you some ideas.

Similar Messages

  • How to make a ScrollPaneLayout that only scrolls vertically?

    I wish to put a number of JTextPanes in a JPanel that is then inside of a JScrollPane which in turn is inside of a JFrame of arbitrary size. Absent the JScrollPane, if you were to narrow the JFrame, the JTextPanes would wrap their text so that they still fit, at least until you run out of vertical space. So, I want to introduce the JScrollPane to create an endless amount of vertical space, but I still want the horizontal space constrained to the size of the JFrame.
    How can I do this? Setting the horizontalScrollPolicy to NEVER simply makes it so the horizontal scrollbar never appears even though the underlying content is still allowed to lay itself out wider than the viewport. Looking at the Javadocs for ScrollPaneLayout and JViewport doesn't turn up anything useful.

    I've tried extending JPanel as shown below and using that as my container for all the JTextPanes and the component that is then the child of the JScrollPane, and it seems to work. I just wish I had some sample implementation of the first 3 methods, particularly the first one.
    public class VerticalScrollPanel extends JPanel implements Scrollable {
    public Dimension getPreferredScrollableViewportSize() {
    return null;
    public int getScrollableUnitIncrement(Rectangle rectangle, int i, int i1) {
    return 1;
    public int getScrollableBlockIncrement(Rectangle rectangle, int i, int i1) {
    return 20;
    public boolean getScrollableTracksViewportWidth() {
    return true;
    public boolean getScrollableTracksViewportHeight() {
    return false;
    }

  • Mighty Mouse Scrolls Vertically in one position (down) only

    I've been using my wireless mighty mouse for about 1 year and it worked fine. recently, I lost the ability to scroll vertically down.
    Has anyone had that problem and/or has any idea on how to fix it.
    I would certainly appreciate any help.
    Thanks.

    Neil,
    Thank you very much. Because the dirt was not visible and I thought I had kept my equipment clean, I never expected that dirt would have been my problem. However, it was.
    Thanks again, I really appreciate this.

  • Hi, While writing an email online using Firefox 3.6.3, I was using one of the "CTRL+left or right arrow" to move the cursor along the text. I must have pressed some other key because the display has become huge - and I can't scroll vertically or horizont

    Hi, While writing an email online using Firefox 3.6.3, I was using one of the "CTRL+left or right arrow" to move the cursor along the text. I must have pressed some other key because the display has become huge - and I can't scroll vertically or horizontally, which makes using the Mail pages of Hotmail impossible. I have since logged in using MSFT Explorer and it works fine. This problem occurs only on the Mail page of Hotmail Live not on the home page or others.
    Could you please let me know if this is a problem with Firefox, or if you have any advice on how to reset the appearance of Hotmail in Firefox?
    == This happened ==
    Just once or twice
    == While I was compiling an email in Hotmail Live

    Wow, lightning fast and absolutely right!
    Thank you so much!

  • Why does the Google home page scroll vertically in Firefox?

    It scrolls vertically only in Firefox. It doesn't scroll when I'm logged out, or if there is a special doodle.

    Can you attach a screenshot?
    *http://en.wikipedia.org/wiki/Screenshot
    *https://support.mozilla.org/kb/how-do-i-create-screenshot-my-problem
    Use a compressed image type like PNG or JPG to save the screenshot.
    Reset the page zoom on pages that cause problems.
    *<b>View > Zoom > Reset</b> (Ctrl+0 (zero); Cmd+0 on Mac)
    *http://kb.mozillazine.org/Zoom_text_of_web_pages
    Clear the cache and the cookies from sites that cause problems.
    "Clear the Cache":
    *Firefox/Tools > Options > Advanced > Network > Cached Web Content: "Clear Now"
    "Remove Cookies" from sites causing problems:
    *Firefox/Tools > Options > Privacy > Cookies: "Show Cookies"
    Start Firefox in <u>[[Safe Mode|Safe Mode]]</u> to check if one of the extensions (Firefox/Tools > Add-ons > Extensions) or if hardware acceleration is causing the problem (switch to the DEFAULT theme: Firefox/Tools > Add-ons > Appearance).
    *Do NOT click the Reset button on the Safe Mode start window or otherwise make changes.
    *https://support.mozilla.org/kb/Safe+Mode
    *https://support.mozilla.org/kb/Troubleshooting+extensions+and+themes

  • How to set a pageBreak for a panel which is scrolling vertically ?

    HI,
    my swing application has a panel which 'll scroll vertically dynamically according to the input.It has to get printed.I used panel.printAll(g) in the printable interface.But the problem is, it is printing only that is visible in the panel.The remaining image/data is not printing.Help me to set the page Break and print the whole panel.

    Quit double and triple posting a questions: [http://forums.sun.com/thread.jspa?threadID=5365422&tstart=0]
    Learn how to use the forum properly. There is an "edit" icon on the top right of you posting that allows yous to edit your question.
    I'm not going to bother to answser your questions until you bother to learn how to use the forum properly.

  • Force a string indicator to scroll to the bottom

    In LV Web UI Builder is there a way to force or programmatically scroll a string indicator to the bottom? 
    I am building a virtual hyperterminal and I am writting a very large amount of data into a string control.  I have the vertical scroll bars turned on, but by default it just shows the information at the top.  I want to include all of the data so that the user can scroll back to see the history, but it would be nice if by default the scroll bar would stay at the bottom.

    I just wanted to confirm there is no way currently to force a string indicator to scroll to the bottom. I will note this down as a product suggestion for the Web UI Builder team.
    Vivek Nath
    National Instruments
    Applications Engineer
    Machine Vision

  • Apple Mouse only scrolls in one direction after 10.6.8 update

    I just updated to 10.6.8 security update, itunes and safari update (I think?) Can't remember now. The update was 10-4-11.
    My Apple mouse now only scrolls in one direction. I thought is was dirty and it is not. There are posted issues with this safarie update with mouse related problems, however I am experiencing them in all programs.
    Rebooted several times, re-cleaned mouse scroll ball, did the paper trick by cleaning. No success.
    I can scroll down but not up. It forces me to grab the scroll bar and manually drag the scrolling window.
    Again ALL programs. Was just fine right before the update. Now a problem after
    Ben

    swb gives good advice. If that didn't work:
    How to really clean your Mighty Mouse (with caution!):
    http://support.apple.com/kb/HT3226?viewlocale=en_US
    and:
    http://web.mac.com/karelgil/iWeb/MacWebSite/MightyMEng.html
    http://www.linklink.co.uk/apple-computers/cleaning-inside-and-dismantling-the-ap ple-mighty-mouse/

  • Pages tear when scrolling vertically

    This is hard to describe, but, with Safari 1.3.1, OS 10.3.9, when I scroll vertically in Safari on SOME web pages (including some Apple pages), the top part of the screen will stay put, while the lower part seems to slide under the upper part. If I scroll far enough, it will suddenly jump into place. On some pages, this happens at different locations across the screen--it may have something to do with frames, dynamic menus, etc. IOW, maybe the center will slide under at a higher (on the screen) location than the right column. It's rather strange. I wondered if it could be some problem with my Kensington trackball with a scroll ring, but I swapped it for the Apple mouse and uninstalled the Kensington software, with no effect. Sometimes, clearing the cache (and, other times, clearing both Java caches) seemed to help, but not always. Also, I found the same problem with my PowerBook, which has never had any non-Apple input device software installed. Also, it happens in Safari and Shiira (which I think uses the same rendering engine as Safari), not in Firefox 1.5 (though the scrolling in Firefox is very jerky, as others seem to have mentioned) nor in iCab. (All except Safari are the latest versions; Safari is the latest version for Panther.)
    Here's a page that shows the problem:
    http://www.apple.com/quicktime/mac.html
    The problem occurs whether I use the scroll ring on the trackball, the arrows on the vertical scroll bar, or click on the thumb button and move it. In some cases, using the page up and page down buttons will avoid the problem, but not always. Moving the cursor over some parts of the page will cause them to suddenly change, even without clicking/selecting anything.
    Any ideas?

    Hi George
    I have had some strange issues like that, including the mouse curser slipping under the top of page. I use an apple mouse. i did not see the problem
    when I clicked on the link u posted it took me to quicktime is that the page you meant?
    Do you run permission repairs for & after software updates, though I do not know if it has anything to do with this it is a nesscessary maintance that helps things running well. Great L4s & some of their links.( organized by Red Dwarf in User Tips)
    a brody = kmosx: General troubleshooting freezes
    http://discussions.apple.com/thread.jspa?threadID=196767
    a brody - kmosx: How to troubleshoot an X issue before posting
    http://discussions.apple.com/thread.jspa?threadID=196766
    Travis A. - kmosx: Regular Maintenance / General Troubleshooting
    http://discussions.apple.com/thread.jspa?threadID=196761
    Gulliver - kmosx: Updating MacOS X: Repair permissions!
    http://discussions.apple.com/thread.jspa?threadID=121709
    best regards, Eme :~{)
    Message was edited by: Eme~ http://discussions.apple.com/thread.jspa?threadID=296514&tstart=0
    Message was edited by: Eme ~~ last is link to user tips

  • Why does my mouse wheel only scroll up in the catalog.  It works correctly in every other program.

    When in a catalog folder and showing a single picture, the mouse wheel only scrolls up, not down.  This behavior is not seen in any program other than elements.  If more than one line of pictures is showing in the window, it works fine, both up and down scrolling.

    Hi All,
    Please refer to the following article and do the needful:
    Photoshop Elements Help | Photoshop Elements hotfix 13.1.1
    It should solve the scrolling issue.
    Thanks,
    Anwesha

  • Forcing a user to only input numbers

    Hey guys! I am writing the code for a game of NIM as an assignment. However, i am having trouble in forcing the user to only input certain things, in this case they are only allowed to enter a number that is less than the total ammount of stones in the pile, but greater than 0 (i.e 1 or more). Now this works fine, and if they enter a letter the NumberFormatException catch handles it fine, but what i am having trouble with is when they enter nothing. They just hit return without actually entering a number. This causes they game to accept that as their turn and go to the next players turn. How would i go about forcing the user to input something. Also if you can give me any clues as to how to make this wny more efficent, it would be very much appreciated! Thank you for your time!
                   do {
                        if ((userStoneChoice > pileTotal) || (userStoneChoice < 1)) {
                             // if the users choice is greater than the ammount of stones in the pile, force them to enter a new number.
                             System.out
                                       .println("Sorry, but there are "+ pileTotal+ " stones in pile "+ pileNumber+
    ".Please ensure you choose a number with that range.");
                             userStoneChoice = Integer.parseInt(in.readLine());
                        } else {
                   } while ((userStoneChoice > pileTotal) || (userStoneChoice < 1));

        private void doUserMove(){
            try{
                userStoneChoice = getUserStoneChoice();
            }catch(IOException ex){
                ex.printStackTrace();
        private int getUserStoneChoice() throws IOException{
            int choice;
            do{
                choice = 0;
                String str = in.readLine();
                try{
                    choice = Integer.parseInt(str);
                }catch( NumberFormatException ex ){}
                if ( choice > pileTotal || choice < 1 ){
                    // if the user's choice is greater than the ammount of stones in the pile,
                    // force them to enter a new number.
                    choice = 0;
                    System.out
                            .println("Sorry, but there are "+ pileTotal+ " stones in pile "+ pileNumber+
                            ".Please ensure you choose a number with that range.");
            } while( choice == 0) ;
            return choice;
        }

  • Parallax Scrolling vertically not working right

    My muse parallax scrolling page will not scroll vertically down the center.  WHen I preview it, the page shifts to the left then scrolls down.  What am I doing worng? Im using Adobe Muse CC.

    Are you getting a scrollbar at the bottom of your browser when your browser is maximized? If yes, there is likely some content (not visible perhaps) placed bit to far to the right on the page.
    Look for the same in Muse in Design View and get rid of the same.
    Share a link to the page with this effect to check if you can't locate the element causing the shift.
    Cheers,
    Vikas

  • When scrolling vertically there is an horizontal line which causes distorsion of the screen. I do not have noticed such concern on my iMac or on my macbook. What happen with the macpro ?

    When scrolling vertically there is an horizontal line which causes distorsion of the screen. I do not have noticed such concern on my iMac or on my macbook. What happen with the macpro ?

    MacPro bought in 2010
    MacBook Pro
    MacBookPro7,1
    Intel Core 2 Duo
    2,4 GHz
      Nombre de processeurs :          1
      Nombre total de cœurs :          2
      Cache de niveau 2 :          3 Mo
      Mémoire :          4 Go
      Vitesse du bus :          1,07 GHz
      Version de la ROM de démarrage :          MBP71.0039.B0B
      Version SMC (système) :          1.62f6
      Numéro de série (système) :          W804853GATP
      UUID du matériel :          716CB476-983B-5C43-B363-988FB608C01C
      Capteur de mouvement brusque
    État :          Activé
    System:
    Mac OS X 10.6.7 (10J869)
    Darwin 10.7.0
    Video DIsplay Card
    NVIDIA GeForce 320M :
      Jeu de composants :          NVIDIA GeForce 320M
      Type :          Processeur graphique (GPU)
      Bus :          PCI
      VRAM (totale) :          256 Mo
      Fournisseur :          NVIDIA (0x10de)
      Identifiant du périphérique :          0x08a0
      Identifiant de révision :          0x00a2
      Révision de la ROM :          3533
      Moniteurs :
    LCD couleur :
      Résolution :          1280 x 800
      Profondeur de pixels :          Couleurs 32 bits (ARGB8888)
      Miroir :          Activé
      État du miroir :          Miroir matériel
      Connecté :          Oui
      Intégré :          Oui
    Is that what you asked ?  Do you need other data ?
    Note that I have also strong distorison when running slides show with iphoto.
    Thanks

  • Scroll Vertically should not possible in Table Control

    Hi,
    In Screen Painter (SE51), we created a Table control program. It's working fine but we want that User cann't able to scroll Vertically.
    In Table Control Properties, there is a option for Fix Column. From here, we can fix the columns but we want to Fix the Rows.
    Please guide...

    Hi,
    In the PBO of the subscreen. Assign some value to the tablecontrol-lines field as below;
    Describe table itab_for_tablecontrol lines tablecontrol-lines.
    OR
    Tablecontrol_lines = 10.
    Regards,
    Karthik D

  • How to force RH9 to use only one master stylesheet for all Word imports?

    I have set a stylesheet (css) as the default for my RH9 WebHelp project in project settings. When I import Word documents into the project, the edit import setting dialog does not show this stylesheet in the list of available stylesheets for the import.
    What is happening instead is a proliferation of unwanted stylesheets derived from all the imported documents. I then have to manually re-set all the new topics to the master stylesheet.
    How can I stop this, and force RH9 to use only the one master stylesheet for all imports?

    cid:[email protected]
    Hi Peter,
    That’s what I thought I was doing in the Project Settings>Import tab>CSS for Style Mapping selection. Maybe that isn’t what it’s meant to do. It’s just getting annoying having all these unneeded files popping up in the project manager so that I have trouble distinguishing the “real” topics from the extra stuff.
    Michael West | Business Improvement | Aurecon
    Ph: +61 3 8683 1996 | Fax: +61 3 8683 1444 | Mob: 0407 485 228
    Email: [email protected]
    PO Box 321, South Melbourne | VIC 3205 | Australia
    http://www.aurecongroup.com
    http://www.aurecongroup.com/apac/groupentity/

Maybe you are looking for

  • Average of the column in ALV report

    Hi,   I am working on an ALV report and for one of the column, i am calculating the average with fieldcatalog property do_sum = 'C'. I am sorting the output table for 2 fields and whenever I am expanding/compressing the sorted fields the average of t

  • It seems that Google search is not compatable with Firefox 9.0.1? Any fixes for this?

    I just upgraded to Firefox 9.0.1 Suddenly, my Google toolbar search does not work. Any work around or fix for this?

  • Vendor Evaluation - GR Cancell handling

    Dear All, Vendor Evaluation scores are calculated for each goods receipt carried out. However, if I goods receipt is posted incorrectly and the GR is subsequently cancelled the on-time delivery score is not reset. Please advise whether there is anywa

  • Accessing SOAP header information in a custom adaptor module

    Hi Guys, Could anyone point me in the direction of information on how to access the SOAP:Header element when writing a custom adaptor module for a http/ SOAP communication channel? I'm trying to add some WS-Security stuff which isn't available in XI

  • Enhancement for QA32 Inspection lot stock tabs

    Hello everybody:    In QA32  user can do UD operation in "Characteristics" tabs and do Posting operation in "Inspection lot stock" tabs.    phase 1: I use QEVA0010 enhancement to check UD  in "Characteristics" tabs and it works.    phase 2: I need to