Stop JcomboBox dropdown

Hi everyone,
I have a requirement to not allow the dropdown list of JComboBox to pop up in certain situations. I could disable the combo box, but that is not the preferred option. I tried to over write JComboBox.firePopupMenuWillBecomeVisible(). The problem with that is: the drop down list (which is a pop up) is already set to visible at this time.
Any suggestion?
Thanks,
Genseng

this might be one way
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.plaf.basic.BasicComboBoxUI;
import javax.swing.plaf.basic.BasicComboPopup;
class Testing extends JFrame
  JComboBox cbo = new JComboBox(new String[]{"London","Madrid","New York","Rome","Sydney","Washington"});
  JRadioButton rb = new JRadioButton("No Popup");
  public Testing()
    setLocation(400,300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    cbo.setUI(new MyUI());
    JPanel jp = new JPanel();
    jp.add(rb);
    jp.add(cbo);
    getContentPane().add(jp);
    pack();
    rb.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent ae){
        if(rb.isSelected()) cbo.setUI(new MyUI_NoPopup());
        else cbo.setUI(new MyUI());}});
  class MyUI extends BasicComboBoxUI
    protected javax.swing.plaf.basic.ComboPopup createPopup()
      return super.createPopup();
  class MyUI_NoPopup extends BasicComboBoxUI
    protected javax.swing.plaf.basic.ComboPopup createPopup()
      BasicComboPopup popup = (BasicComboPopup)super.createPopup();
      popup.setPreferredSize(new Dimension(0,0));
      return popup;
  public static void main(String args[]){new Testing().setVisible(true);}
}

Similar Messages

  • JComboBox dropdown table list

    Hi,
    Any helps will be very appreciated.
    I have a problem in the JCombobox dropdown list. I want to have multiple columns in the dropdown list of the JComboBox, eg. when I type something in the JComboBox, it will query some infomation from the Database. The Database will return more 3 fields of the query results. I would like to have these three fields stored in the table format as JComboBox drowdown list. When I select a row and only one of the columns will be displayed in the JComboBox.
    Thanks a lot
    Catherine

    I found these posts in about 10 seconds ...
    http://forum.java.sun.com/thread.jsp?forum=57&thread=330533
    http://forum.java.sun.com/thread.jsp?forum=57&thread=160944
    http://forum.java.sun.com/thread.jsp?forum=57&thread=379524

  • Resize JComboBox dropdown doesn't work without customized ListCellRenderer

    Based on the forum thread Horizontal scrollbar for JComboBox across multiple look and feel , the following code will work, if only I provide a customized ListCellRenderer (A JPanel with several JLabels).
    FYI, here is my ListCellRenderer code [http://jstock.cvs.sourceforge.net/viewvc/jstock/jstock/src/org/yccheok/jstock/gui/ResultSetCellRenderer.java?view=markup]
    Here is the code which adjust the drop down list width. The setup instruction is exactly same as the one mentioned in forum by Kleopatra
        private void adjustPopupWidth() {
            if (this.getItemCount() == 0) return;
            Object comp = this.getUI().getAccessibleChild(this, 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());
            Dimension prefSize = rendererComp.getPreferredSize();
            Dimension size = scrollPane.getPreferredSize();
            size.width = Math.max(size.width, prefSize.width);
            scrollPane.setPreferredSize(size);
            scrollPane.setMaximumSize(size);
            scrollPane.revalidate();
        }However, when come to a JComboBox, without explicitly provided it a list cell renderer, the above code will have NPE being thrown at line
           Component rendererComp = this.getRenderer().getListCellRendererComponent(null, value, 0, false, false);
           // Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
           // at javax.swing.plaf.basic.BasicComboBoxRenderer.getListCellRendererComponent(BasicComboBoxRenderer.java:94)Hence, I modify the code as follow and hoping it will work.
        private void adjustPopupWidth() {
            if (this.getItemCount() == 0) return;
            Object comp = this.getUI().getAccessibleChild(this, 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);
            Component rendererComp = this.getRenderer().getListCellRendererComponent((JList)scrollPane.getViewport().getView(), value, 0, false, false);       
            if (rendererComp instanceof JXTable) {
                scrollPane.setColumnHeaderView(((JTable) rendererComp).getTableHeader());
            Dimension prefSize = rendererComp.getPreferredSize();
            Dimension size = scrollPane.getPreferredSize();
            size.width = Math.max(size.width, prefSize.width);
            scrollPane.setPreferredSize(size);
            scrollPane.setMaximumSize(size);
            scrollPane.revalidate();
        }No more exception being thrown this time. Just that my dropdown list doesn't resize at all when I have a long String. It remains normal size as usual, with horizontal scrollbar being shown to catter the long String.
    Is there anything I had missed out?
    Thanks
    Edited by: yccheok on Oct 23, 2010 9:40 PM
    Edited by: yccheok on Oct 23, 2010 9:41 PM

    Yes. The problem solved. Out of curiosity, is it necessary to have statement? As I remove it, it just work as well.
    scrollPane.revalidate();I include SSCCE for this problem.
    package sandbox;
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.JList;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.plaf.basic.BasicComboPopup;
    * @author yccheok
    public class NewJFrame extends javax.swing.JFrame {
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
        /** 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);
            getContentPane().setLayout(new java.awt.FlowLayout());
            jComboBox1.setEditable(true);
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Long Long Long Long Item 4" }));
            jComboBox1.setPreferredSize(new java.awt.Dimension(80, 20));
            jComboBox1.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
                public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
                public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                    jComboBox1PopupMenuWillBecomeVisible(evt);
            getContentPane().add(jComboBox1);
            pack();
        }// </editor-fold>
        private void jComboBox1PopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            adjustPopupWidth();
        * @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);
        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 = jComboBox1.getItemAt(0);
            Component rendererComp = jComboBox1.getRenderer().getListCellRendererComponent((JList)scrollPane.getViewport().getView(), value, 0, false, false);
            //if (rendererComp instanceof JXTable) {
            //    scrollPane.setColumnHeaderView(((JTable) rendererComp).getTableHeader());
            //Dimension prefSize = rendererComp.getPreferredSize();
            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);
            //scrollPane.revalidate();
        // Variables declaration - do not modify
        private javax.swing.JComboBox jComboBox1;
        // End of variables declaration
    }

  • Put a divider/separator into a JComboBox dropdown menu

    Hello,
    I need to put a separator of some sort into the dropdown menu of my JComboBox. Has anyone acheived this successfully? I don't know the best way to go about it, so any advice would be much appreciated.
    Thanks,
    Lauren.

    http://forum.java.sun.com/thread.jsp?forum=57&thread=125320

  • Multiple Linux JComboBox drops in the same position

    Following program create two similar JComboBox dropdown, and in Linux, when it runs, it works weirdly.
    If I first click first dropdown (s1), then later when I click second one (s2), dropdown part still appears under the first component.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class JBugClass {
         public static void main(String[] args) {
              JFrame frame = new JFrame("BugClass AWT version");
              Container pane = frame.getContentPane();
              String[] items = { "Item 1", "Item 2", "Item 3" };
              JComboBox s1 = new JComboBox(items);
              JComboBox s2 = new JComboBox(items);
              JButton wx = new JButton("QUIT");
              wx.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        System.exit(0);
              pane.setLayout(new FlowLayout(FlowLayout.LEFT));
              pane.add(s1);
              pane.add(s2);
              pane.add(wx);
              frame.pack();
              frame.setVisible(true);
    }I created separated string arrays for s1 and s2, but position is still incorrect. It works completely fine in Windows. I am now suspecting that this is a bug of Linux J2SE1.4.0. Does anyone know any workaround?

    All of the features you're asking for are very easy to add and control in LabVIEW once you know what you're looking for. To show the Front Panel of a SubVI, open the VI and navigate to its "Customize Window Appearance" window (this is in File>VI Properties, select Category: Window Appearance, then click "Customize"). Check the "Show Front Panel when called" checkbox.
    However, there are quite a few other properties you'll likely want to edit as well, so it would be best to review the LabVIEW Topic: "Customize Window Appearance Dialog Box".
    In your main VI, put the SubVI in the True case of a Case Structure, then connect your button to the selector terminal. The more complex behavior your asking for can be achieved using multiple case structures.
    Matt Kirk
    Inventor of ImageJVI

  • Dynamic parameter not bringing in all values/Pagination of dropdown values

    Hello,
    I have a dynamic (but not cascading) prompt in a Crystal 2008 SP3 report. It uses a view to bring in a list of customers.
    The underlying view returns about 1800 or so rows, but the prompt is not bringing in any more than about approx 1000 rows.
    I seem to remember this being an issue with the old Crystal reports and thought there was some kind of limitation to no more than 1000 rows unless some registry hack is performed.
    Is this still true with CR 2008 and if so, what is the correct registry setting to change this?
    Another related question (less critical than the first) -
    In my report, the prompt dropdown is "paginating" the results, so about 200 or so rows per dropdown page, with 5 pages.
    Is there a way to stop the dropdown prompt from paginating the results over multiple pages? It is awkward to have to go from page to page in the dropdown, and the filter is useful and a good workaround but wanted to know if there was a way to stop the pagination.
    Thank you

    Go to the following regsistry path
    HKEY_LOCAL_MACHINE\SOFTWARE\Business Objects\Suite 12.0\Crystal Reports\DatabaseOptions\LOV
    and add the following STRING entry (if it does not exist)
    MaxRowsetRecords
    Set the value to 2000 or whatever number you need.
    Do you retrieve the values over a universe or a direct database connection?
    Regards,
    Stratos

  • JComboBox Dropping Problem

    Hi, I have a JComboBox in a table cell with all the Item I need. But the problem is when I click on JComboBox, dropdown menu pops up and immediately hides automatically. And cannot allow me to choose anything.
    Any suggestions plz.
    Thanks

    You've got a coding problem, so read this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html]How to Use Combo Boxes for example on how to do this correctly.

  • JComboBox in OSX

    hello,
    i have a question about JComboBox in Mac OSX. At the windows machine it
    looks ok.
    In OSX the JCombobox Dropdown-List is not aligned to the left side from the component when selected, i say 5 pixels to the left.
    And when the application window is dragged the combobox needs a bit of seconds to place to the correct new place.
    At windows everything works fine. Has this to do with my code or is it normal with swing under OSX ?
    regards,
    marco

    Also, If it is a new document that you're saving for the first time open the advanced saving options by clicking the drop down triangle after the Save as: line. Not only will this give you more options as to where you'd like to save you document but at the bottom you'll see a box that says "Save copy as a word document." click that box. You should then have a word and a pages version of your document.

  • Combo box popup width adjusting no longer work in 1.0.6_26-b03

    Previously, I was able to adjusting combo box popup's width, by referring to the technique described in [http://tips4java.wordpress.com/2010/11/28/combo-box-popup/|http://tips4java.wordpress.com/2010/11/28/combo-box-popup/]. During that time, I was using 1.0.6_24-b07.
    However, after I update my Java runtime to 1.0.6_26-b03, things broke.
    Here is the screen shoot.
    [Workable screen shoot|http://i.imgur.com/0elo7.png]
    [Not workable screen shoot|http://i.imgur.com/BeKMy.png]
    Here is the code snippet to demonstrate this problem.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    * NewJFrame.java
    * Created on Aug 9, 2011, 4:13:41 AM
    package experiment;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import javax.swing.JComboBox;
    import javax.swing.JList;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    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 {
         * Adjust popup for combo box, so that horizontal scrollbar will not display.
         * Resize JComboBox dropdown doesn't work without customized ListCellRenderer
         * http://www.camick.com/java/source/BoundsPopupMenuListener.java
         * @param comboBox The combo box
        public static void adjustPopupWidth(JComboBox comboBox) {
            if (comboBox.getItemCount() == 0) return;
            Object comp = comboBox.getAccessibleContext().getAccessibleChild(0);
            if (!(comp instanceof BasicComboPopup)) {
                return;
            BasicComboPopup popup = (BasicComboPopup)comp;
            JList list = popup.getList();
            JScrollPane scrollPane = getScrollPane(popup);
            // Just to be paranoid enough.
            if (list == null || scrollPane == null) {
                return;
            //  Determine the maximimum width to use:
            //  a) determine the popup preferred width
            //  b) ensure width is not less than the scroll pane width
            int popupWidth = list.getPreferredSize().width
                            + 5  // make sure horizontal scrollbar doesn't appear
                            + getScrollBarWidth(popup, scrollPane);
            Dimension scrollPaneSize = scrollPane.getPreferredSize();
            popupWidth = Math.max(popupWidth, scrollPaneSize.width);
            //  Adjust the width
            scrollPaneSize.width = popupWidth;
            scrollPane.setPreferredSize(scrollPaneSize);
            scrollPane.setMaximumSize(scrollPaneSize);
         *  I can't find any property on the scrollBar to determine if it will be
         *  displayed or not so use brute force to determine this.
        private static int getScrollBarWidth(BasicComboPopup popup, JScrollPane scrollPane) {
            int scrollBarWidth = 0;
            Component component = popup.getInvoker();
            if (component instanceof JComboBox) {
                JComboBox comboBox = (JComboBox)component;
                if (comboBox.getItemCount() > comboBox.getMaximumRowCount()) {
                    JScrollBar vertical = scrollPane.getVerticalScrollBar();
                    scrollBarWidth = vertical.getPreferredSize().width;
            return scrollBarWidth;
         *  Get the scroll pane used by the popup so its bounds can be adjusted
        private static JScrollPane getScrollPane(BasicComboPopup popup) {
            JList list = popup.getList();
            Container c = SwingUtilities.getAncestorOfClass(JScrollPane.class, list);
            return (JScrollPane)c;
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
            this.jComboBox1.addPopupMenuListener(getPopupMenuListener());
        /** 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", "This is a very long text. This is a very long text" }));
            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(82, 82, 82)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(242, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(34, 34, 34)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(246, 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);
        private PopupMenuListener getPopupMenuListener() {
            return new PopupMenuListener() {
                @Override
                public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                    // We will have a much wider drop down list.
                    adjustPopupWidth(jComboBox1);
                @Override
                public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                @Override
                public void popupMenuCanceled(PopupMenuEvent e) {
        // Variables declaration - do not modify
        private javax.swing.JComboBox jComboBox1;
        // End of variables declaration
    }

    I had came across another workaround as stated here.
    [http://www.jroller.com/santhosh/entry/make_jcombobox_popup_wide_enough|http://www.jroller.com/santhosh/entry/make_jcombobox_popup_wide_enough]
    The popup's is having enough width to show all items. However, it is not perfect still, as the width is little too much. I still can see some extra space at the tailing of the list.
    The workaround is as follow.
    import javax.swing.*;
    import java.awt.*;
    import java.util.Vector;
    // got this workaround from the following bug:
    //      http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4618607
    public class WideComboBox extends JComboBox{
        public WideComboBox() {
        public WideComboBox(final Object items[]){
            super(items);
        public WideComboBox(Vector items) {
            super(items);
        public WideComboBox(ComboBoxModel aModel) {
            super(aModel);
        private boolean layingOut = false;
        public void doLayout(){
            try{
                layingOut = true;
                super.doLayout();
            }finally{
                layingOut = false;
        public Dimension getSize(){
            Dimension dim = super.getSize();
            if(!layingOut)
                dim.width = Math.max(dim.width, getPreferredSize().width);
            return dim;
    }

  • How to create a button with the drop-down menu?

    I want to create a button with the drop-down menu, which is like the 'back' on the tollbar in IE. I heard JPopupMenu can reach the certain result, but the button hadn't a down arrow. Who can help me?

    i have made something like this :
    //======================================================================
    package com.ju.guiutils
    import java.awt.*;
    import java.awt.event.*;
    import java.net.URL;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.plaf.basic.BasicComboBoxUI;
    * @version 1.0 14/04/02
    * @author Syed Arshad Ali <br> [email protected]<br>
    * <B>Usage : </B> ButtonsCombo basically performs function button + JComboBox, if we have different options for
    * <BR>same button then we can use this ButtonsCombo.
    *<BR> By the way there is no button at all in <I>ButtonsCombo</I>
    public class ButtonsCombo extends JComboBox {
    //===================================================================================
    * Create ButtonsCombo with default combobox model
    public ButtonsCombo () {
    super ();
    init ();
    //===================================================================================
    * Creates a ButtonsCombo that takes it's items from an existing ComboBoxModel.
    public ButtonsCombo ( ComboBoxModel model ) {
    super ( model );
    init ();
    //===================================================================================
    * Creates a ButtonsCombo that contains the elements in the specified array.
    public ButtonsCombo ( Object [] items ) {
    super ( items );
    init ();
    //===================================================================================
    * Creates a ButtonsCombo that contains the elements in the specified Vector.
    public ButtonsCombo ( Vector items ) {
    super ( items );
    init ();
    //===================================================================================
    private void init () {
    setBorder ( BorderFactory.createBevelBorder ( BevelBorder.RAISED ) );
    setRenderer ( new ComboRenderer() );
    setUI ( new ComboUI() );
    addMouseListener ( new ComboMouseListener() );
    //===================================================================================
    * Set items for ButtonsCombo in the specified array
    public void setItems ( Object [] items ) {
    setModel ( new DefaultComboBoxModel( items ) );
    //```````````````````````````````````````````````````````````````````````````````````
    * Set items for ButtonsCombo in the specified Vector
    public void setItems ( Vector items ) {
    setModel ( new DefaultComboBoxModel( items ) );
    //```````````````````````````````````````````````````````````````````````````````````
    * Get current items in a array
    public Object [] getItemsArray () {
    ComboBoxModel model = this.getModel ();
    if ( model != null ) {
    int size = model.getSize ();
    if ( size > 0 ) {
    Object [] items = new Object[ size ];
    for ( int i = 0; i < size; i++ ) {
    items[ i ] = model.getElementAt ( i );
    return items;
    return null;
    //```````````````````````````````````````````````````````````````````````````````````
    * Get current items in a Vector
    public Vector getItemsVector () {
    ComboBoxModel model = this.getModel ();
    if ( model != null ) {
    int size = model.getSize ();
    if ( size > 0 ) {
    Vector itemsVec = new Vector();
    for ( int i = 0; i < size; i++ ) {
    itemsVec.addElement ( model.getElementAt ( i ) );
    return itemsVec;
    return null;
    //===================================================================================
    class ComboMouseListener extends MouseAdapter {
    public void mouseClicked ( MouseEvent me ) {
    ButtonsCombo.this.hidePopup ();
    public void mousePressed ( MouseEvent me ) {
    ButtonsCombo.this.hidePopup ();
    ButtonsCombo.this.setBorder ( BorderFactory.createBevelBorder ( BevelBorder.LOWERED ) );
    public void mouseReleased ( MouseEvent me ) {
    ButtonsCombo.this.hidePopup ();
    ButtonsCombo.this.setBorder ( BorderFactory.createBevelBorder ( BevelBorder.RAISED ) );
    //===================================================================================
    class ComboRenderer extends JLabel implements ListCellRenderer {
    //````````````````````````````````````````````````
    public ComboRenderer () {
    setOpaque ( true );
    //````````````````````````````````````````````````
    public Component getListCellRendererComponent ( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus ) {
    setBackground ( isSelected ? Color.cyan : Color.white );
    setForeground ( isSelected ? Color.red : Color.black );
    setText ( ( String )value );
    return this;
    //````````````````````````````````````````````````
    //===================================================================================
    // We have to use this class, otherwise we cannot stop JComboBox's popup to go down
    class ComboUI extends BasicComboBoxUI {
    public JButton createArrowButton () throws NullPointerException {
    try {
    URL url = getClass ().getResource ( "/images/comboarrow.gif" );
    JButton b = new JButton( new ImageIcon( url ) );
    b.addActionListener ( new ActionListener() {
    public void actionPerformed ( ActionEvent ae ) {
    return b;
    } catch ( NullPointerException npe ) {
    throw new NullPointerException( "/images/comboarrow.gif not found or /images folder not in classpath" );
    catch ( Exception e ) {
    e.printStackTrace ();
    return null;
    //======================================================================
    you can cutomize this according to your requirement , okie ;)

  • Why listener methods are getting called twice ?

    Hi Group,
    I have a doubt, i need to know logic behind it.
    Lets consider, JComboBox,
    For an item state change of JComboBox,
    itemStateChanged method gets called twice.
    Its similar with valueChanged getting called twice
    on List Selection Event.
    Why does it call twice ? Is there any way, I can
    have invocation only once (except flagging mechanism)?
    with regards,
    vikram.

    http://java.sun.com/j2se/1.3/docs/api/java/awt/event/ItemListener.html
    tells the following:
    public void itemStateChanged(ItemEvent e)
    Invoked when an item has been selected or deselected. The code written for this method performs the operations that need to occur when an item is selected (or deselected).
    So the listener is notified for both items: losing and gaining selection.
    If you are only interested in listening to either selection or deselection event you can check which was the cause for the method call by examing the ItemEvent parameter i.e. item_event.getStateChange() == ItemEvent.DESELECTED or ItemEvent.SELECTED and then decide whether you are interested in the event at all.
    I don't know how to stop JComboBox from launching both select and deselected events.

  • Determine the best width for ListCellRenderer - Multi-column combo box

    Currently, I am having a multi column combo box. In order for the column to align properly during show popup, I use box layout to do so. However, the short coming for box layout is that, the size for each column is fixed. This makes me have a difficulty, when I have a long string to be displayed. The problem is shown through the following screen shoot.
    http://i.imgur.com/4Nfc6.png
    This is because in 2nd column,
    1) All the 3 rows must be in same size so that they are aligned.
    2) But 1st row and 2nd row cell renderer, do not know 3rd row is holding such a long string.
    The code (2 files) to demo this problem is as follow. Is there any way the size of the cell will be adjusted automatically? Yet, all the row will be aligned properly.
    ResultSetCellRenderer.java
    package javaapplication24;
    import java.awt.Color;
    import java.awt.Component;
    import javaapplication24.NewJFrame.ResultType;
    import javax.swing.JList;
    import javax.swing.ListCellRenderer;
    import javax.swing.UIManager;
    * @author yccheok
    public class ResultSetCellRenderer extends javax.swing.JPanel implements ListCellRenderer {
        /** Creates new form ResultSetCellRenderer */
        public ResultSetCellRenderer() {
            initComponents();
        /** 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() {
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.X_AXIS));
            jLabel1.setText("jLabel1");
            jLabel1.setMaximumSize(new java.awt.Dimension(88, 14));
            jLabel1.setMinimumSize(new java.awt.Dimension(88, 14));
            jLabel1.setPreferredSize(new java.awt.Dimension(88, 14));
            add(jLabel1);
            jLabel2.setText("jLabel2");
            jLabel2.setMaximumSize(new java.awt.Dimension(100, 14));
            jLabel2.setMinimumSize(new java.awt.Dimension(200, 14));
            jLabel2.setPreferredSize(new java.awt.Dimension(100, 14));
            add(jLabel2);
        }// </editor-fold>
        // Variables declaration - do not modify
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        // End of variables declaration
        // Do not use static, so that our on-the-fly look n feel change will work.
        private final Color cfc  = UIManager.getColor("ComboBox.foreground");
        private final Color cbc  = UIManager.getColor("ComboBox.background");
        private final Color csfc = UIManager.getColor("ComboBox.selectionForeground");
        private final Color csbc = UIManager.getColor("ComboBox.selectionBackground");
        private final Color cdfc = UIManager.getColor("ComboBox.disabledForeground");
        // For Nimbus look n feel.
        private final Color nimbus_csfc;
             Color c = UIManager.getColor("ComboBox:\"ComboBox.renderer\"[Selected].textForeground");
             // Pretty interesting. Applying "c" directly on the component will not
             // work. I have the create a new instance of Color based on "c" to make
             // it works.
             nimbus_csfc = c != null ? new Color(c.getRed(), c.getGreen(), c.getBlue()) : null;
        private final Color nimbus_csbc;
            Color c = UIManager.getColor("ComboBox:\"ComboBox.renderer\"[Selected].background");
             // Pretty interesting. Applying "c" directly on the component will not
             // work. I have the create a new instance of Color based on "c" to make
             // it works.
            nimbus_csbc = c != null ? new Color(c.getRed(), c.getGreen(), c.getBlue()) : null;
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            final Color _csbc = csbc != null ? csbc : nimbus_csbc;
            final Color _csfc = csfc != null ? csfc : nimbus_csfc;
            this.setBackground(isSelected ? _csbc : cbc);
            this.setForeground(isSelected ? _csfc : cfc);
            jLabel1.setBackground(isSelected ? _csbc : cbc);
            jLabel1.setForeground(isSelected ? _csfc : cfc);
            jLabel2.setBackground(isSelected ? _csbc : cbc);
            jLabel2.setForeground(isSelected ? _csfc : cfc);
            final ResultType result = (ResultType)value;
            jLabel1.setText(result.symbol);
            jLabel2.setText(result.name);
            return this;
    NewJFrame.java
    package javaapplication24;
    import java.awt.Container;
    import java.awt.Dimension;
    import javax.swing.JComboBox;
    import javax.swing.JList;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    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 {
        public static class ResultType {
             * The symbol.
            public final String symbol;
             * The name.
            public final String name;
            public ResultType(String symbol, String name) {
                this.symbol = symbol;
                this.name = name;
            @Override
            public String toString() {
                return symbol;
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
            this.jComboBox1.addPopupMenuListener(this.getPopupMenuListener());
            this.jComboBox1.setRenderer(new ResultSetCellRenderer());
            this.jComboBox1.addItem(new ResultType("Number 1", "Normal"));
            this.jComboBox1.addItem(new ResultType("Number 2", "Normal"));
            this.jComboBox1.addItem(new ResultType("Number 3", "A VERY VERY VERY VERY long text"));
        /** 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);
            getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jComboBox1ActionPerformed(evt);
            getContentPane().add(jComboBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 110, -1));
            pack();
        }// </editor-fold>
        private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    final NewJFrame frame = new NewJFrame();
                    frame.setVisible(true);
        private PopupMenuListener getPopupMenuListener() {
            return new PopupMenuListener() {
                @Override
                public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                    // We will have a much wider drop down list.
                    adjustPopupWidth(jComboBox1);
                @Override
                public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                @Override
                public void popupMenuCanceled(PopupMenuEvent e) {
         * Adjust popup for combo box, so that horizontal scrollbar will not display.
         * Resize JComboBox dropdown doesn't work without customized ListCellRenderer
         * http://www.camick.com/java/source/BoundsPopupMenuListener.java
         * @param comboBox The combo box
        public static void adjustPopupWidth(JComboBox comboBox) {
            if (comboBox.getItemCount() == 0) return;
            Object comp = comboBox.getAccessibleContext().getAccessibleChild(0);
            if (!(comp instanceof BasicComboPopup)) {
                return;
            BasicComboPopup popup = (BasicComboPopup)comp;
            JList list = popup.getList();
            JScrollPane scrollPane = getScrollPane(popup);
            // Just to be paranoid enough.
            if (list == null || scrollPane == null) {
                return;
            //  Determine the maximimum width to use:
            //  a) determine the popup preferred width
            //  b) ensure width is not less than the scroll pane width
            int popupWidth = list.getPreferredSize().width
                            + 5  // make sure horizontal scrollbar doesn't appear
                            + getScrollBarWidth(popup, scrollPane);
            Dimension scrollPaneSize = scrollPane.getPreferredSize();
            popupWidth = Math.max(popupWidth, scrollPaneSize.width);
            //  Adjust the width
            scrollPaneSize.width = popupWidth;
            scrollPane.setPreferredSize(scrollPaneSize);
            scrollPane.setMaximumSize(scrollPaneSize);
         *  I can't find any property on the scrollBar to determine if it will be
         *  displayed or not so use brute force to determine this.
        private static int getScrollBarWidth(BasicComboPopup popup, JScrollPane scrollPane) {
            int scrollBarWidth = 0;
            JComboBox comboBox = (JComboBox)popup.getInvoker();
            if (comboBox.getItemCount() > comboBox.getMaximumRowCount()) {
                JScrollBar vertical = scrollPane.getVerticalScrollBar();
                scrollBarWidth = vertical.getPreferredSize().width;
            return scrollBarWidth;
         *  Get the scroll pane used by the popup so its bounds can be adjusted
        private static JScrollPane getScrollPane(BasicComboPopup popup) {
            JList list = popup.getList();
            Container c = SwingUtilities.getAncestorOfClass(JScrollPane.class, list);
            return (JScrollPane)c;
        // Variables declaration - do not modify
        private javax.swing.JComboBox jComboBox1;
        // End of variables declaration
    }Edited by: yccheok on Jan 13, 2011 9:35 AM

    Are these two lines intentionally or is it just a mismatch?
    jLabel2.setMaximumSize(new java.awt.Dimension(100, 14));
    jLabel2.setMinimumSize(new java.awt.Dimension(200, 14));
    2) But 1st row and 2nd row cell renderer, do not know 3rd row is holding such a long string.There is only one cell renderer for all rows, so no need for the rows to know each other.
    To calculate the exact maximum width of column two, you have to check each entry.
    If you can do this BEFORE creating the combo, you could do this in a loop similar to this pseudo code
    FontMetrics fm= jComboBox1.getFontMetrics(jComboBox1.getFont());
    foreach (column2String) {
      int length= fm.stringWidth(column2String);
      if (length>max) max= length;
    }Now you have a max value to dimension jLabel2 in your renderer.
    If you don't fill your combo in one go, but rather at runtime, you have to check at each
    jComboBox1.addItem(...)
    whether the string for label2 is extending the current max, redefine max, and repaint the combo.
    This second approach I haven't done so far, but that's how I would try.

  • AdjustPopupWidth will not work properly, if there is a vertical scrollbar

    Previously, I am using "adjustPopupWidth", so that my JComboBox will be width enough, to display all the items in drop down list.
    However, I realize when there is present of vertical scrollbar, "adjustPopupWidth" will not generate a correct width, to display all items in the drop down list. This cause a horizontal scrollbar to be shown as well (which is not what I want)
    An example of code is as follow :
    * 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
    }Removing "Item 1" till "Item 7", will cause vertical scroll bar not being shown. Hence, "adjustPopupWidth" will work correctly.
    It seems that the calculation within "adjustPopupWidth", should take account into the vertical scroll bar. But how?
    Thanks.

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

  • When i try to download an update the dropdown automatically inserts my apple id which is wrong. It's in gray and will not allow me to type in a correct id. How do I stop / delete the automatic insertion of the id?

    When i try to download an update from the appstore the dropdown  menju automatically inserts my apple id (which is wrong). It's in gray and will not allow me to type in the correct id. How do i stop the auto insert so that i can enter the correct id?

    the original apple id was entered incorrectly. Apple says it must be a email address.  My email address is correct but the letter ( t ) somehow got added to the (.com) so that when i try to enter my id it is automaticly loaded with the email address the ends ( .comt ) . According to Apple this is not a "legal" email id.  But it appears on my dropdown in gray and i cannot alter it or delete it, thus preventing me from downloading software updates.

  • DropDown in JComboBox

    Hallo
    Does someone know, how i can set the width of the DropDown-Menu from the JComboBox manually??
    i want that the list is larger than the width of the JComboBox.
    thx for help :)
    eagle

    That link above might not work so just use:
    http://www.objects.com.au/java/examples/swing/SteppedComboBox.do

Maybe you are looking for

  • What will I lose by removing a folder and then resynchronizing?

    I am having a problem editing files that I imported into Lightroom from my photoshop elements 6 catalog. The details of what I've gone through are in the thread titled: Problem with "Edit in Photoshop" and Lightroom 2.1 failing to import new file I t

  • Borderless Printing issues with HP Officejet 4500

    I have created a document using Microsoft word 2007 and am having trouble printing this document without borders. I have a HP Officejet 4500 which does support borderless printing. I have gone into properties when getting ready to print and made sure

  • My G4 MDD Dual 1.25 wont do ANYTHING AT ALL

    It was behaving normally and I powered it down last night before I went to sleep. When I woke up this morning expecting to be productive I tried turning on the computer and NOTHING happened at all. No fans, no hard drives, no nothing. I tried turning

  • Default SSL context init failed: DerInputStream.getLength(): lengthTag=109,

    Hi I am trying to connect to an https:// url using java (digital certificates) and send an xml file to it and get the response.. I have server certificate stored in our m/c..and password.. I am getting following exception ->>> Default SSL context ini

  • Profit center required in cost center

    Hi All How can i make profit center field is required in the cost center master data? Please anybody give the idea Regards Sekhar