Wiki
Wiki

Reputation: 235

How to pad a combo box?

I am using JComboBox in my application, I would like to increase the padding. All the initial contents in my combo box are aligned very closely to the left border, so I want to pad it so that it looks somewhat legible.

This is some sample code I use in my application:

jPanelPatientInfo.add(jComboBoxNation, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0,   
GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 10, 0, 0), 0, 0));

Upvotes: 0

Views: 1882

Answers (3)

Gilbert Le Blanc
Gilbert Le Blanc

Reputation: 51445

I'm assuming you want to increase the padding on the inside of the JComboBox (the list part). You need to be more specific when asking a question.

Here's one way to pad the inside of a JComboBox.

import java.awt.Component;

import javax.swing.DefaultListCellRenderer;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;

public class BorderListCellRenderer implements ListCellRenderer {

    private Border insetBorder;

    private DefaultListCellRenderer defaultRenderer;

    public BorderListCellRenderer(int rightMargin) {
        this.insetBorder = new EmptyBorder(0, 2, 0, rightMargin);
        this.defaultRenderer = new DefaultListCellRenderer();
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value,
            int index, boolean isSelected, boolean cellHasFocus) {
        JLabel renderer = (JLabel) defaultRenderer
                .getListCellRendererComponent(list, value, index, isSelected,
                        cellHasFocus);
        renderer.setBorder(insetBorder);
        return renderer;
    }

}

Then, you use the class like this.

JComboBox comboBox = new JComboBox(elements);
comboBox.setRenderer(new BorderListCellRenderer(20));

Upvotes: 2

camickr
camickr

Reputation: 324118

The easiest way to give your components more space on a panel is to add a Border to the panel. It looks like you are using a GridBagLayout so the code would be Something like:

JPanel panel = new JPanel( new GridBagLayout() );
panel.addBorder( new EmptyBorder(10, 10, 10, 10) );
panel.add(component1, constraints);

Now if you add components on different rows they will all be indented 10 pixels.

Upvotes: 1

alex.p
alex.p

Reputation: 2739

Try calling setPrototypeDisplayValue on the combobox. This will set the width based on the amount of text used. As mentioned in the linked documentation, if this is not there then it uses the preferred width basing this on the size of each element.

Upvotes: 0

Related Questions