Avatar of Javin007
Javin007
Flag for United States of America asked on

Proper way to resize JComboBox Width, locking Height only?

Seems like this should be simple, but a few hours on Google has only confused me more.

I have a JComboBox that I want to be locked to a specific height, not the default height.

I want to be able to add items to this box, and have it resize its width to fit the "longest" object.

Any combination of setPreferredSize() that I've used seems to lock both, not just the one.  Your help is appreciated.
JavaJava EEProgramming Languages-Other

Avatar of undefined
Last Comment
mccarl

8/22/2022 - Mon
mccarl

Can you post a small compilable example that demonstrates what you are seeing? It would help a great deal and make it easier to get a solution for you.
Javin007

ASKER
Unfortunately the project I'm working on isn't on this network.  I'd have to download/install Eclipse to create a demo.

But it's very simple.  Create a window, add a combobox to it.  Now shrink the combobox's height, but still have it able to automatically size its width as you add items to it.
Javin007

ASKER
I've requested that this question be deleted for the following reason:

No answers after several days.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
mccarl

Does you delete request also mean that you were able to solve your issue? Or find a workaround?

If not, I'm still willing to help you. It has just been a few days since I last posted because I don't have much of a chance to post over the weekend.
Javin007

ASKER
I still haven't found a solution, but if you have one, I can certainly pull the delete request out!
mccarl

But it's very simple.  Create a window, add a combobox to it.  Now shrink the combobox's height, but still have it able to automatically size its width as you add items to it
It's actually not as simple as that. There are a number of different ways of creating a combobox, and a number of different ways of "adding" items to it. I understand why you were not able to create an example, but just saying for the future, it will generally get you an answer faster if you are able to provide something that we can work off.

Ok, so making some wild assumptions about the above variables, I created the following code that was able to do what (I think) you want...
import java.awt.Dimension;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestComboboxSizing extends JFrame {
    
    public TestComboboxSizing() {
        super("Test Combobox Sizing");
        
        setPreferredSize(new Dimension(640, 480));
        
        JPanel panel = new JPanel();
        add(panel);
        
        JComboBox comboBox = new JComboBox(new String[] { "Small item", "A very, very, very big item", /*"An even biggggggggggggggggggggggggggggggger item"*/ });
        
        Dimension preferredSize = comboBox.getPreferredSize();
        preferredSize.height = 10;
        comboBox.setPreferredSize(preferredSize);
        
        panel.add(comboBox);
        
        pack();
    }
    
    public static void main(String[] args) {
        new TestComboboxSizing().setVisible(true);
    }
}

Open in new window

Obviously, lines 19-21 are the main part of the solution. And by changing what items populate the combo box, I was able to confirm that the width does indeed change to fit the longer items, while the height remains constrained.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Javin007

ASKER
Unfortunately, this code actually creates the entire box at the beginning, so it sizes off of the initial setup.  Here's an example of what I'm looking for:

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JFrame {
    
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected static JComboBox<String> comboBox = null;
	
	public Test() {
        super("Test Combobox Sizing");
        
        setPreferredSize(new Dimension(640, 480));
        
        JPanel panel = new JPanel();
        add(panel);
        
        comboBox = new JComboBox<String>();
        comboBox.addItem("Small String");
        
        Dimension preferredSize = comboBox.getPreferredSize();
        preferredSize.height = 20;
        comboBox.setPreferredSize(preferredSize);
        
        JButton btnAdd = new JButton("Test");
        btnAdd.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				addNewItem();
			}
		});
        
        panel.add(comboBox);
        panel.add(btnAdd);
        
        pack();
    }
    
    public static void main(String[] args) {
        new Test().setVisible(true);
    }
    
    public static void addNewItem() {
    	comboBox.addItem("Very very long item entry.");
    	//TODO: This is where the combobox needs to be resized.
    }
    
}

Open in new window



When you press the "Test" button it will add another item that is longer than the comboBox.  The comboBox needs to resize itself at that point.
ASKER CERTIFIED SOLUTION
mccarl

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Javin007

ASKER
Brilliant!  I'd tried grabbing the preferred size after adding the item before and gotten nowhere.  The answer was setting the preferred size to NULL prior to adding the new item!  This works perfectly!

-Javin
Javin007

ASKER
I've requested that this question be closed as follows:

Accepted answer: 500 points for mccarl's comment #a39682452
Assisted answer: 0 points for Javin007's comment #a39685162

for the following reason:

*  Selected own comment for clarification purposes only.  McCarl's solution was perfect.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
mccarl

I'm glad that we were able to come to a solution for you! :)