adjustPopupWidth will not correctly work if there is a vertical scroll bar

Previously, I use "adjustPopupWidth", so that my JComboBox will enough width to display all items in the drop-down list.

However, I realize when he is present of the vertical scroll bar, 'adjustPopupWidth' will not produce a good width to display all the items in the drop-down list. This causes a horizontal scrollbar to appear as well (which is not what I want)

A code example is as follows:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewJFrame.java
 *
 * Created on Dec 30, 2010, 12:35:42 AM
 */

package javaapplication24;

import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JPopupMenu;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.basic.BasicComboPopup;

/**
 *
 * @author yccheok
 */
public class NewJFrame extends javax.swing.JFrame {

    // Resize JComboBox dropdown doesn't work without customized ListCellRenderer
    private void adjustPopupWidth() {
        if (jComboBox1.getItemCount() == 0) return;
        Object comp = jComboBox1.getUI().getAccessibleChild(jComboBox1, 0);
        if (!(comp instanceof JPopupMenu)) {
            return;
        }
        JPopupMenu popup = (JPopupMenu) comp;
        JScrollPane scrollPane = (JScrollPane) popup.getComponent(0);

        //Object value = this.getItemAt(0);
        //Component rendererComp = this.getRenderer().getListCellRendererComponent(null, value, 0, false, false);
        //if (rendererComp instanceof JXTable) {
        //    scrollPane.setColumnHeaderView(((JTable) rendererComp).getTableHeader());
        //}
        BasicComboPopup basic = (BasicComboPopup)comp;
        Dimension prefSize = basic.getList().getPreferredSize();
        Dimension size = scrollPane.getPreferredSize();

        size.width = Math.max(size.width, prefSize.width);
        scrollPane.setPreferredSize(size);
        scrollPane.setMaximumSize(size);
        // Do we need to call revalidate?
        //scrollPane.revalidate();
    }

    private void adjustScrollBar() {
        final int max_search = 8;
        // i < max_search is just a safe guard when getAccessibleChildrenCount
        // returns an arbitary large number. 8 is magic number
        JPopupMenu popup = null;
        for (int i = 0, count = jComboBox1.getUI().getAccessibleChildrenCount(jComboBox1); i < count && i < max_search; i++) {
            Object o = jComboBox1.getUI().getAccessibleChild(jComboBox1, i);
            if (o instanceof JPopupMenu) {
                popup = (JPopupMenu)o;
                break;
            }
        }
        if (popup == null) {
            return;
        }
        JScrollPane scrollPane = null;
        for (int i = 0, count = popup.getComponentCount(); i < count && i < max_search; i++) {
            Component c = popup.getComponent(i);
            if (c instanceof JScrollPane) {
                scrollPane = (JScrollPane)c;
                break;
            }
        }
        if (scrollPane == null) {
            return;
        }
        scrollPane.setHorizontalScrollBar(new JScrollBar(JScrollBar.HORIZONTAL));
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    }

    private PopupMenuListener getPopupMenuListener() {
        return new PopupMenuListener() {
            @Override
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                // We will have a much wider drop down list.
                adjustPopupWidth();
            }

            @Override
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            }

            @Override
            public void popupMenuCanceled(PopupMenuEvent e) {
            }
        };
    }

    /** Creates new form NewJFrame */
    public NewJFrame() {
        initComponents();
        // Have a wide enough drop down list.
        jComboBox1.addPopupMenuListener(this.getPopupMenuListener());
        adjustScrollBar();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "long long long long long string", "Item 8", " " }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(140, 140, 140)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(152, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(269, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JComboBox jComboBox1;
    // End of variables declaration

}
Remove 'Item 1' up to 'Article 7', results in a vertical scroll bar is not displayed. Therefore, "adjustPopupWidth" will work correctly.

It seems that the calculation within the "adjustPopupWidth", should take into account in the bar vertical scrolling. But how?

Thank you.

[url http://www.camick.com/java/blog.html?name=combo-box-popup] Combo Box Popup handles this.

Tags: Java

Similar Questions

  • There is a vertical scroll bar?

    Scrolling at the time often gets hurt interpreted double click? I would like to see a more positive control for scrolling, such as a similar to the buttons Windows or scrolling scroll bar up and scroll down.

    Scrolling on a touchscreen is definitely an art and not 'intuitive '. However, I do not remember see the scroll bars in the Android applications, then perhaps it isn't done (or not done easily) on this platform?

  • EDGE file will not correctly work DPS! Any ideas on what I could do?

    I built an EDGE file up to the size of a layout of iPad full screen (1024 X 768), with a few elements that animate it. I set up correctly and, published "animate Deployment Package. However, when playing in DPS, there is a hesitation (or delay), then, a white - stop in action - then the animation plays very well. I've not coded late or stops.

    I'm not a coder.

    I did several tests with a variety of images of "Post", but I always get the "Hesitation" (of late) room.

    Can you let me know what I'm not doing correctly?

    Thank you!

    I think I know what you're talking about.

    Try the following steps.  First of all in Indesign set your auto play animation and set a deadline for 0.125.  I talked with Adobe and they will set a guideline always have a 0.125 for animations created with Edge delay.  Second, make sure you check "Transparent background" and "scale content worthy."  The good thing is that it is full screen and set to 1024.

    Make sure that you also define an image of the poster on board if you do not receive the empty image until he began to play on the iPad.  Another thing.  DC animations are essentially controlled by Safari on the iPad, you will see a longer than 1/8 of a second that you define.  I attribute that to the iPad have to load it on request before time.

    I hope this helps.

    Ryan.

  • CF cards will not correctly work with El Capitan

    Using a San Disk USB 3 card reader and the CalDigit FASTA 6GU3 + the PCI card. Everything works fine with 10.8.6, but with El Capitan, I can't copy anything that either of the maps - it hangs then ejects the card and I get an error message that the operation cannot be completed because error i/o and the drive was not ejected. Card back immediately, but the problems of the rehearsals. Boot in sys old and everything is good, then it seems to be a problem of El Cap have deleted previous CALDIGIT drivers for my previous card (which does not work with El Cap), so this isn't the problem.

    Did you mean 10.6.8 Snow Leopard?  There is no Cougar maxed out at 10.8.5 10.8.6.  If you mean the snow leopard, a lot of software is not compatible with 10.7 or later is with older versions.  There should be compatible Compact Flash readers on multifunction printers, as well as some readers you might find http://www.macsales.com

    If it's the same machine that came with 10.6, you can also install 10.6 on another partition or an external hard drive, or if it's a newer than July 20, 2011 Mac, you must put the option run Snow Leopard Server on your Mac.

    Rosetta/PowerPC applications and Lion and above

  • WebFonts and Typekit fonts will not correctly work in Windows7 Chrome

    I tried almost all the browsers for Windows 7 and Chrome is always the black sheep for me (surprisingly not IE). Many fonts typekit and webfonts look perfect in Muse, Muse Preview, IE and Firefox.

    But when I open the Chrome, the horror begins.

    I use this cool site Dani of Muse jams posted for this demonstration (site is not me): http://www.pmorenofotografo.com/

    Google Chrome:

    chrome.jpg

    Notice how the menu looks like all the "pixelated".

    And it's the same site in Firefox:

    firefox.jpg

    The menu seems perfect.

    This problem is making me spend more time choosing the right font for my sites, I'm sure everybody wants their site to look perfect on all browsers out there.

    I used another site to prove that the issue was not my Web sites. Furthermore, none of my sites have this question cause I have spend hours to find fonts that do not resemble this on Chrome.

    Hi Seruhio,

    What you see here is in fact a difference in how Chrome and rendering of fonts. Unfortunately, there is nothing that can be done about it. Chrome font rendering is, for some fonts, not very good, and the only way to really know is to check the appearance of your fonts in the browser. If you are interested, Typekit team made a very long series of blog posts on the difference in rendering of fonts for the web, including recommendations for policies that make it well. Positions are at this point a few years old, but they are still very useful in learning about differences.

  • E520 w / 6630M 2GB card will not correctly work with OpenGL "Advanced" setting in Adobe Photoshop CS5.5

    I'm having a problem using the "Advanced" setting OpenGL in Adobe Photoshop CS5.5. While I can choose "Advanced" option, any of the advanced features are available for use (as the panoramic film and animated zoom).

    I updated my system with the latest video drivers (8.840.7.3000/6.14.0.3074) and BIOS (1.22/1.10/1.02), however, does not.

    Video drivers packed on the Lenovo site aren't the last registered on the site of AMD for the 6630M and I can't update my system with the drivers from the website of AMD.

    It is a real problem for me since I bought the laptop as a machine of design production and may not use the graphics card to its full potential. I wrote to AMD to ask them, which resulted in pushing them as stake of Lenovo.

    Update: last updated driver (8.882.2.3000 / 6.14.0.3074) fixed a problem
    http://support.Lenovo.com/en_US/downloads/detail.page?docid=DS014099

  • Deskjet 6122 driver will not properly work on a HP Proliant ML 150 6 Win Server

    Deskjet 6122 driver will not properly work on a HP Proliant ML 150 6 server running Window server 2003 Enterprise edition SP2. I have loaded driver 990c and it works, but the side two the 6122 print function will not work with 990c. Is there any solution for this?

    I'm afraid that there is no specific driver for this OS. The 990c driver will be the only option to get to work. I'm sorry.

  • The update of Firefox will not now work update 2-3 days ago.

    Set Firefox to update if there is 2-4 days and since that time arrives, but won't do anything. He knows the previous sites on the drop-down list but will not load anything on the web. The top bar shows the following:http://en-gb.start3.mozilla.com/firefox?client=firefox-a & rls = org.mozilla: en - GB:official

    One possible cause is a firewall is not blocking the new version of Firefox, for more details, see Firefox cannot load websites, but can other browsers.

  • Adobe Reader 11.0.10, will not print.  Mssg "There are no selected pages" How do I print?

    Adobe Reader 11.0.10, will not print.  Mssg 'There are no selected pages', even with selected pages.  I tried 'Image', same mssg err. ;  Printer has the latest drivers.  Printer prints everything (browsers, docs, .xls), but not Adobe.  Used vacuum to unistall, received error message: 5 on GetNamedSecurityInfoand could not define Loyer.  Any help would be greatly appreciated.  THX

    Assuming you're on Windows, try changing the following preferences

    • Documents: series "Show the documents in PDF/A mode" Never
    • (Protection): Disable "protected at Startup Mode.
  • Vertical scroll bar not working not properly on Internet Explorer 11

    The vertical scroll bar does not work on the Favorites menu for example. When you scroll down the Favorites until you can click your choice, it bounces up to the top.

    I have windows 7, IE11 and java. I saw a similar query for vista and the suggestion is to click on "smooth scrolling" in the section advanced options, but this has already been clicked.

    It's very frustrating.

    Something similar is happening under him start / all programs bar vertical, but not as bad.

    Thank you

    Paul

    Hi Paul,.

    Glad to know that the problem is solved.

    Will you please post in the Microsoft Community for any help in Windows and we will be happy to help you.

  • After recommending the bios update, hp dv6131od running xp pro sp3 will not load windows - is there a wa

    After installing an update of the bios recommended on the hp website my dv6131od running xp pro sp3 will not load windows

    Update does not seem to have problems - failure, lack of time for flash, backup, etc.

    boot sequence seems normal (finds it a bootable cd in the drive, etc.), but windows won't load in safe or other mode

    next steps?  is there a way to access the BIOS?

    Thank you

    There is a simple solution to this problem.  The HP Online Crash Analysis Team has finally responded to my email after 34 days.  I had given up hearing from them despite several requests to repeat.

    I had completely disassembled the laptop trying to find the bios setting the jumpers on the motherboard in response to an idea contained in one of the PM, I sent... all to nothing does not...

    OCAT told me to look in the BIOS under "system configuration" for the Native SATA support.  The last update of the BIOS resets this point 'activated', but that only works for Vista & Win 7.  This must be set to "disabled" for XP and previous operating system.

    I hope that this post will save someone having to wait 5 weeks invest hours of work for a solution that took 3 minutes!

  • Cursor will not correctly display on my H243H monitor

    When I connect my H243H monitor to my laptop (running Windows 7 Edition Home Premium - 64-bit), the cursor will not display on the monitor correctly.  I either get no cursor visible at all or I get a small rectangular grey box.  All solutions?  I went to check the monitor driver, but Acer demonstrated only a 32-bit driver available.  This could be the problem and is it possible around it?  Thanks in advance for your suggestions.

    You have another computer, you can test it? I guess it's a setting on the computer, because the only problem seems to be the cursor. There are some settings that you can change and solutions, you can try the link below.

    http://superuser.com/questions/590569/broken-mouse-cursor-on-main-monitor-Windows-7-64-bit-ATI-Radeo...

  • WMC will not correctly record programmes

    I can't get WMC to save my TV programs properly... for some reason when I have scheduled to record a certain program, it will rather to record any show I am watching both (or more if I'm zapping).  He won't even hit the correct program if I am not watching TV... only the last channel, I watched.  I noticed that when I did the original of WMC, when I got to the section where it asks to enter a three-digit channel (I also tried a camera digital two also), it will not change the channel at all.  I tried the option asking you if I need to press ENTER or OK after the channel number and the option when I press the channel number only.  Neither work.  WMC does not seem to recognize my remote fully, even if I used it without any problems before.  I think it has to do with the fact that I have changed TV providers and now need a box set, which I never used before.

    My tv tuner is a Hauppauge WinTV-PVR-USB2 and my tv provider is Telus Optik and my OS is Vista Home Premium(32-bit).  If anyone has any ideas, I would greatly appreciate.

    Thanks in advance!

    To clarify, since you are using a box, he will be able to record the channel on the box is currently defined.

    Think Media Center is your TV, if you change your TV to channel 10, it won't get any signal. You must keep your TV to a specific channel and change the channel on the box. If Media Center is unable to change the channel on the box, the correct exposure will not be saved.

    You said that when you have tested, it would change the channel. As I mentioned, you must run the installer once more and check if the channels are changing and, if necessary, adjust the settings accordingly.

    David
    Microsoft Answers Support Engineer
    Visit our Microsoft answers feedback Forum and let us know what you think.

  • Windows Explorer and other programs will not open / work

    Can anyone help? In XP Home Edition, programs as internet explore/microsoft works work only sporadically, but often does not open and then I asks me to send an error report. When I try to stop, Windows Explorer will not work and asks me to send another report of error! ... Can not much experience with these things someone explain what I can do? (I ran a virus scan, and all seems ok)
    Thank you

    Hi Mike,.

    According to my experience, this kind of behaviour is symptomatic of the corruption of data on the hard drive. However, since you say that these applications work sometimes I am inclined to suspect that your hard drive may be failing, possibly with errors in sector where those applications reside.

    I suggest that you take a backup copy of the any of your own data files and then run a CHKDSK command on your hard drive to see what he finds (this can make a right click on the HARD drive in my computer icon, then select Properties, then the Tools tab.) Check disk utility is at the top).

    If it detects too many bad sectors, and then looking to replace the hard drive and reinstalling your system.

    Kind regards

  • Vista will not print works wireless but wired through router

    I have 2 wireless modem ATT DSL wire connected to a firewall server / print wireless Netgear FM114P ProSafe and a router 3Com to increase the number of connections.

    I have a Vista laptop that allows to print everything wired through my 3Com router connected to th Netgear FM114P ProSafe, server print/firewall wireless connected to a HP laserjet 6 p printer, but while Vista connects to wireless internet, it won't print wireless HP connected to the print server.

    I have configured the other portable XP to print wireless using the same ip address but can't get Vista to work.

    Hello

    Your 2 wire wireless mode, is actually a Modem/Router combo.

    I hope that your Prosafe device is connected as a switch with an Access Point.

    If it is connected as a second router you have independent networks that will not work against the second router NAT doble and thustwo.

    Re-set according to the principle here, http://www.ezlan.net/router_AP.html

    Jack-MVP Windows Networking. WWW.EZLAN.NET

Maybe you are looking for