views:

445

answers:

2

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.

+1  A: 

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!

Jeach
Gabi
A: 

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