什么是 Swing-equivalent to HTML <optgroup> [英] What is the Swing-equivalent to HTML &lt;optgroup&gt;

查看:13
本文介绍了什么是 Swing-equivalent to HTML <optgroup>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的 JComboBox 将多个选项组合在一起,类似于 HTML optgroup:

I want my JComboBox to group multiple options together, similar to the HTML optgroup:

<select>  
 <optgroup label="A">  
  <option/>
  <option/>  
 </optgroup>
</select>  

我在 Swing 中找不到任何解决方案.操作 Combobox 的 UI-Renderer 似乎是一个坏主意,因为它是 OS &L&F 依赖(它们是私有的,因此无法扩展).

I could not find any solution for this in Swing. Manipulating the UI-Renderer for the Combobox seems to be a bad idea, as it's OS & L&F-dependent (and they are private so cannot extend).

推荐答案

考虑将以下实现作为如何应用自定义样式和创建不可选择的项目的基本指南:

Consider the following implementation as a basic guide how to apply custom styling and create non-selectable items:

public class ExtendedComboBox extends JComboBox {

    public ExtendedComboBox() {
        setModel(new ExtendedComboBoxModel());
        setRenderer(new ExtendedListCellRenderer());
    }

    public void addDelimiter(String text) {
        this.addItem(new Delimiter(text));
    }

    private static class ExtendedComboBoxModel extends DefaultComboBoxModel {
        @Override
        public void setSelectedItem(Object anObject) {
            if (!(anObject instanceof Delimiter)) {
                super.setSelectedItem(anObject);
            } else {
                int index = getIndexOf(anObject);
                if (index < getSize()) {
                    setSelectedItem(getElementAt(index+1));
                }
            }
        }

    }

    private static class ExtendedListCellRenderer 
                    extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList list, Object value,
                        int index, boolean isSelected, boolean cellHasFocus) {
            if (!(value instanceof Delimiter)) {
                return super.getListCellRendererComponent(list, value, index,
                        isSelected, cellHasFocus);
            } else {
                JLabel label = new JLabel(value.toString());
                Font f = label.getFont();
                label.setFont(f.deriveFont(f.getStyle() 
                           | Font.BOLD | Font.ITALIC));
                return label;
            }
        }
    }

    private static class Delimiter {
        private String text;

        private Delimiter(String text) {
            this.text = text;
        }

        @Override
        public String toString() {
            return text.toString();
        }
    }
}

这篇关于什么是 Swing-equivalent to HTML <optgroup>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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