编程语言
首页 > 编程语言> > java – 什么是Swing – 相当于HTML

java – 什么是Swing – 相当于HTML

作者:互联网

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

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

我在Swing找不到任何解决方案.操作Combobox的UI-Renderer似乎是一个坏主意,因为它是OS&依赖于L& F(它们是私有的,所以不能延伸).

解决方法:

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

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();
        }
    }
}

标签:optgroup,java,swing,combobox
来源: https://codeday.me/bug/20190927/1824138.html