Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

java - Remove border from JComboBox

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...