Solved

Proper way to resize JComboBox Width, locking Height only?

Posted on 2013-11-21
11
2,643 Views
Last Modified: 2013-11-29
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.
0
Comment
Question by:Javin007
  • 6
  • 5
11 Comments
 
LVL 35

Expert Comment

by:mccarl
ID: 39667770
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.
0
 
LVL 4

Author Comment

by:Javin007
ID: 39669273
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.
0
 
LVL 4

Author Comment

by:Javin007
ID: 39685168
I've requested that this question be deleted for the following reason:

No answers after several days.
0
 
LVL 35

Expert Comment

by:mccarl
ID: 39676254
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.
0
 
LVL 4

Author Comment

by:Javin007
ID: 39676325
I still haven't found a solution, but if you have one, I can certainly pull the delete request out!
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 35

Expert Comment

by:mccarl
ID: 39679576
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.
0
 
LVL 4

Author Comment

by:Javin007
ID: 39681232
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.
0
 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
ID: 39682452
If you look through some of the source code for the Swing components, it appears that "preferredSize" gets tracked at the Dimension level, not the individual width & height level, so I am pretty sure that you can only set the pair, not just one or the other.

So, this is what I could come up with. It does feel like a bit of a hack, but I think it could be the only way. It should be pretty self explanatory, just add everything via the addNewItem method, or do the equivalent to what that method is doing, ie. if you were adding multiple items, you should be able to null the preferredSize at the start, and set it again appropriately after adding all items.
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>();
        addNewItem("Small String");
        
        JButton btnAdd = new JButton("Test");
        btnAdd.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				addNewItem("Very very long item entry.");
			}
		});
        
        panel.add(comboBox);
        panel.add(btnAdd);
        
        pack();
    }
    
    public void addNewItem(String item) {
        comboBox.setPreferredSize(null);

    	comboBox.addItem(item);

    	Dimension preferredSize = comboBox.getPreferredSize();
    	preferredSize.height = 15;
    	comboBox.setPreferredSize(preferredSize);
    }

    public static void main(String[] args) {
        new Test().setVisible(true);
    }
    
}

Open in new window

0
 
LVL 4

Author Comment

by:Javin007
ID: 39685162
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
0
 
LVL 4

Author Comment

by:Javin007
ID: 39685175
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.
0
 
LVL 35

Expert Comment

by:mccarl
ID: 39685249
I'm glad that we were able to come to a solution for you! :)
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now