Invoke revalidate() on the panel containing the combobox. This will cause the components to be layed out again based on their preferred sizes.
This is the same concept as adding/removing a component on a visible GUI.
Edit:
Just reread your question. I'm not sure if you can dynamically resize the popup when it is open but you can check out Combo Box Popup. It shows you how to override the preferred width of the popup. This code is executed when the popup menu is about to be shown. But you may be able to use the concepts to access the popup and change the width dynamically.
Edit 2:
Here is an example that shows the basic concept. The popup will adjust its width every 2 seconds. However, I don't know if this will help with your problem because if you are dynamicallyl adding/removing items from the popup, then you will need to recreate the popup every time the popup is changed. This will probably result in the popup hiding/showing which means you will need to live with a little flicker anyway.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class ComboBoxExample extends JPanel implements ActionListener
{
private JComboBox comboBox;
public ComboBoxExample()
{
String[] petStrings = { "Select Pet", "Bird", "Cat", "Dog", "Rabbit", "Pig", "Other" };
comboBox = new JComboBox( petStrings );
add( comboBox, BorderLayout.PAGE_START );
Timer timer = new javax.swing.Timer(2000, this);
timer.start();
}
public void actionPerformed(ActionEvent e)
{
comboBox.showPopup();
Object child = comboBox.getAccessibleContext().getAccessibleChild(0);
BasicComboPopup popup = (BasicComboPopup)child;
JList list = popup.getList();
Container c = SwingUtilities.getAncestorOfClass(JScrollPane.class, list);
JScrollPane scrollPane = (JScrollPane)c;
Dimension size = scrollPane.getSize();
if (size.width > 20)
size.width -= 5;
scrollPane.setPreferredSize(size);
scrollPane.setMaximumSize(size);
Dimension popupSize = popup.getSize();
popupSize.width = size.width;
Component parent = popup.getParent();
parent.setSize(popupSize);
parent.validate();
parent.repaint();
Window mainFrame = SwingUtilities.windowForComponent(comboBox);
Window popupWindow = SwingUtilities.windowForComponent(popup);
// For heavy weight popups you need to pack the window
if (popupWindow != mainFrame)
popupWindow.pack();
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame( "ComboBoxExample" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
JComponent newContentPane = new ComboBoxExample();
newContentPane.setOpaque( true );
frame.setContentPane( newContentPane );
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…