3

Do you know any way to remove the border from a JComboBox in Java? I try the following code

public class ComboFrame extends JFrame {
    public ComboFrame() {
        JPanel container = new JPanel();

        JComboBox cmb = new JComboBox(new String[] { "one", "two" });
        cmb.setBorder(BorderFactory.createEmptyBorder());
        container.add(cmb);

        getContentPane().add(container);
        pack();
    }
}

and

public static void main(String[] args) throws Exception {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            new ComboFrame().setVisible(true);
        }
    });
}

Don't ask why would someone want to remove the border from a combobx... I guess it does not make too much sense, but this is how it's wanted, and I got really curious if it can be done. I tried several tricks, but none of them worked.

The most effective was changing the UI with

cmb.setUI(new BasicComboBoxUI());

This makes the border go away, but alters the L&F, and I need to keep the Windows L&F if possible.

Thanks.

Gabriel
  • 2,313
  • 9
  • 29
  • 41

2 Answers2

5

I did a bit of research and found this bug

I tried it for myself and it does seem to affect the border. You might want to try one or both of the following code blocks for yourself.

for (int i = 0; i < combo.getComponentCount(); i++) 
{
    if (combo.getComponent(i) instanceof JComponent) {
        ((JComponent) combo.getComponent(i)).setBorder(new EmptyBorder(0, 0,0,0));
    }


    if (combo.getComponent(i) instanceof AbstractButton) {
        ((AbstractButton) combo.getComponent(i)).setBorderPainted(false);
    }
}

It is important to note that at the bottom of the bug entry, you can read the following:

The JButton maintains it's own border so JComponent paintBorder() and paintComponent() has no awareness of the JComboBox border.

Good luck,

Jeach!

Community
  • 1
  • 1
Jeach
  • 8,656
  • 7
  • 45
  • 58
  • Thanks Jeach! This works indeed for the default L&F (Metal). But on Windows, with the system L&F, it still does not want to work... – Gabriel Apr 29 '09 at 10:07
  • 6 years later, thank you for this answer! I was trying to change the color of an editable jcombobox and could only do so after setting its editor to the metal type. However, this caused an ugly border to surround the box. Using the JComponent loop cleared up the box and the background is set nicely – tenwest Mar 19 '15 at 20:03
0

If you want to use the windows L&F, you can do cmd.setUI(new WindowsComboBoxUI()); If you, however, want to be able to use any L&F, you might be better off using the solution proposed by Jeach.

Markus Jevring
  • 832
  • 1
  • 11
  • 17