簡體   English   中英

自定義JComboBox頂級標簽

[英]custom JComboBox top label

希望是一個簡單的問題。

http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/components/combobox.html上的“提供自定義渲染器”部分的示例中,我可以制作一個JComboBox

Picture 3 - Text 3
-------------------
Picture 1 - Text 1
Picture 2 - Text 2
Picture 3 - Text 3
Picture 4 - Text 4
Picture 5 - Text 5

Picture 3 - Text 3是當前選擇的項目。

是否可以擁有自定義標簽?

Text 3
-------------------
Picture 1 - Text 1
Picture 2 - Text 2
Picture 3 - Text 3
Picture 4 - Text 4
Picture 5 - Text 5

當組合框處於最小化狀態時,不顯示圖像。

我之前使用過JButton /未修飾的彈出式JFrame來模擬它,但我想知道是否可以使用純JComboBox

謝謝

是否可以擁有自定義標簽? 如...

是。 相同的渲染器用於渲染下拉列表和組合框中的選定項。 當“渲染器索引”為-1時,所選值為渲染器,因此您可以根據需要自定義渲染。 就像是:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;

public class ComboBoxItemIcon extends JFrame
{
    public ComboBoxItemIcon()
    {
        Vector model = new Vector();
        model.addElement( new Item(new ImageIcon("copy16.gif"), "copy" ) );
        model.addElement( new Item(new ImageIcon("add16.gif"), "add" ) );
        model.addElement( new Item(new ImageIcon("about16.gif"), "about" ) );

        JComboBox comboBox;

        comboBox = new JComboBox( model );
        comboBox.setRenderer( new ItemRenderer() );
        getContentPane().add(comboBox, BorderLayout.SOUTH );
    }

    class ItemRenderer extends BasicComboBoxRenderer
    {
        public Component getListCellRendererComponent(
            JList list, Object value, int index,
            boolean isSelected, boolean cellHasFocus)
        {
            super.getListCellRendererComponent(list, value, index,
                isSelected, cellHasFocus);

            Item item = (Item)value;

            if (index == -1)
            {
                setText( item.getText() );
                setIcon( null );
            }
            else
            {
                setText( item.getText() );
                setIcon( item.getIcon() );
            }

            return this;
        }
    }

    class Item
    {
        private Icon icon;
        private String text;

        public Item(Icon icon, String text)
        {
            this.icon = icon;
            this.text = text;
        }

        public Icon getIcon()
        {
            return icon;
        }

        public String getText()
        {
            return text;
        }
    }

    public static void main(String[] args)
    {
        JFrame frame = new ComboBoxItemIcon();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible( true );
     }

}

渲染中似乎有3個與顯示圖像和文本相關的函數調用:

setIcon setText setFont

我沒有編譯這個例子,但我會嘗試注釋掉setIcon(icon); 從函數getListCellRendererComponent,因為它似乎顯示所選項目的圖像。

如果評論它會破壞代碼,那么我會嘗試覆蓋一個空白圖像或某些東西作為解決方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM