如何使JCombobox看起来像JTextField [英] How to make JCombobox look like a JTextField

查看:162
本文介绍了如何使JCombobox看起来像JTextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种好的(简单的)方法可以使JCombobox看起来像JTextField?
我的意思是不应该有一个下拉按钮,但是当用户输入内容时它应该显示多种结果。

Is there a good(and easy) way to make a JCombobox look like a JTextField? By this I mean there should not be a dropdown button, but when the user enters something it should show multible results.

基本上与google,youtube相同,facebook等工作。

Basically the same way google, youtube, facebook etc. works.

推荐答案

JComboBox comboBox = new JComboBox();
comboBox.setUI(new BasicComboBoxUI() {
    @Override
    protected JButton createArrowButton() {
        return new JButton() {
            @Override
            public int getWidth() {
                return 0;
            }
        };
    }
});

使getWidth()返回0确保:

a)按钮不是显示

b)没有为它保留空间,让你输入整个字段

Making getWidth() return 0 ensures that:
a) the button is not shown
b) no space is reserved for it, letting you type in the whole field

我发现我必须调用 .setUI()通过 SwingUtilities.invokeLater(),但根据代码的结构,你可能不需要。

I found that I had to do invoke .setUI() via SwingUtilities.invokeLater(), but depending on the structure of your code, you might not have to.

如果你想要自动完成,可以在组合框中添加一些项目,并使用 AutoCompleteDecorator.decorate(comboBox) AutoCompleteDecorator 类是 SwingX 的一部分,之前提到的。

If you want autocomplete, add some items to the combo box, and use AutoCompleteDecorator.decorate(comboBox). The AutoCompleteDecorator class is part of SwingX, as previously mentioned.

这可能会让你的盒子在使用另一个L&F时看起来很奇怪,所以你必须选择要实例化的CombiBoxUI,以获得正确的外观。

This might make your box look weird when using another L&F, so you will have to choose which CombiBoxUI to instantiate, to get the right look.

如果您不希望在组合框中没有任何内容时显示下拉菜单,请在BasicComboBoxUI中覆盖此方法:

If you do not want the drop-down to appear when there is nothing in the combo box, override this method in the BasicComboBoxUI as well:

@Override
public void setPopupVisible(JComboBox c, boolean v) {
    // keeps the popup from coming down if there's nothing in the combo box
    if (c.getItemCount() > 0) {
        super.setPopupVisible(c, v);
    }
}

这篇关于如何使JCombobox看起来像JTextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆