Jorn Rigter
Jorn Rigter

Reputation: 1205

Remove focus from JComboBox Java Swing

I am trying to remove the dotted line from my JComboBox. The initial ComboBox Initial JComboBox has a dotted line after it has gained focus: After clicked

Now, I want to remove that focus. However I can't find it in the UIManager's options (https://gist.github.com/itzg/5938035). I have looked at this post from May 2018, but the answer is not there yet.

I have tried the following:

  jComboBox.setFocusable(false);
  UIManager.put("ComboBox.focus", new Color(0, 0, 0, 0));

but none of them worked.

Any help would be greatly appreciated!

Upvotes: 1

Views: 941

Answers (1)

ItFreak
ItFreak

Reputation: 2369

You can do the following:

comboBox.setUI(new BasicComboBoxUI());

This will result in the following after an element was selected and get you rid of the dotted border:

enter image description here

For removing any 'kind' of focus border, you need to override the ComboBoxUI which is used for drawing the box and its component.

Here is the code I used to achieve the example:

public ComboboxWithoutDottedBorder() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch(Exception ignored){}
       this.setVisible(true);
       JLabel label = new JLabel("Label");
       JComboBox<String> combo = new JComboBox<>();
       this.setLayout(new BorderLayout());
       combo.addItem("A");
       combo.addItem("B");
       combo.addItem("C");
       combo.addItem("D");
       combo.setUI(new BasicComboBoxUI());

       this.add(label, BorderLayout.NORTH);
       this.add(combo, BorderLayout.SOUTH);
    }

Upvotes: 1

Related Questions