简体   繁体   English

从JComboBox移除边框

[英]Remove border from JComboBox

Do you know any way to remove the border from a JComboBox in Java? 您知道用Java中的JComboBox删除边框的任何方法吗? 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. 不要问为什么有人要从combobx删除边框...我想这没有太大意义,但这就是想要的方式,我真的很好奇是否可以做到。 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. 这样可以使边框消失,但会改变L&F,如果可能,我需要保留Windows L&F。

Thanks. 谢谢。

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. JButton保持其自己的边框,因此JComponent paintBorder()paintComponent()不了解JComboBox边框。

Good luck, 祝好运,

Jeach!

If you want to use the windows L&F, you can do cmd.setUI(new WindowsComboBoxUI()); 如果要使用Windows L&F,可以执行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. 但是,如果您希望能够使用任何L&F,最好使用Jeach提出的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM