国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

用Java創(chuàng)建帶圖標(biāo)和縮進(jìn)的JComboBox

2019-11-18 13:37:35
字體:
供稿:網(wǎng)友

  默認(rèn)的JComboBox無法在每個條目上顯示圖標(biāo)、縮進(jìn)等樣式。但是Swing的MVC設(shè)計(jì)結(jié)構(gòu)為各種組件提供了無與倫比的可擴(kuò)展性。為了實(shí)現(xiàn)這一點(diǎn),我們可以創(chuàng)建一個新的Renderer來負(fù)責(zé)每個條目的繪制。

首先我們新寫一個類ImagedComboBoxItem,它封裝了一個下拉條目的信息,包括圖標(biāo)、文字、縮進(jìn)等:

class ImagedComboBoxItem {
PRivate Icon icon = null;
private String text = null;
private int indent = 0;

ImagedComboBoxItem(String text, Icon icon, int indent) {
this.text = text;
this.icon = icon;
this.indent = indent;
}

public String getText() {
return text;
}

public Icon getIcon() {
return icon;
}

public int getIndent() {
return indent;
}
}

然后新建JImagedComboBox類并從JComboBox繼續(xù)。在構(gòu)造函數(shù)中,新建一個DefaultListCellRenderer作為新的Renderer,并覆蓋其getListCellRendererComponent方法。在新的getListCellRendererComponent方法中,首先依舊調(diào)用父對象的該方法,以便完成普通條目的繪制;然后判定條目是否是ImagedComboBoxItem實(shí)例。假如是,則顯示ImagedComboBoxItem的文字、圖標(biāo),并顯示縮進(jìn)。為了更方便的顯示左側(cè)縮進(jìn),我們直接創(chuàng)建一個EmptyBorder并設(shè)置左側(cè)縮進(jìn)數(shù)量,并設(shè)置到DefaultListCellRenderer中。DefaultListCellRenderer從JLabel繼續(xù)而來,所以可直接接受各種Border。這里我們以每個縮進(jìn)10象素為例。

好了,以下是完整代碼:

import java.util.*;

import java.awt.*;
import javax.swing.*;

public class JImagedComboBox extends JComboBox {
public JImagedComboBox(Vector values) {
super(values);
ListCellRenderer renderer = new DefaultListCellRenderer() {
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof ImagedComboBoxItem) {
ImagedComboBoxItem item = (ImagedComboBoxItem) value;
this.setText(item.getText());
this.setIcon(item.getIcon());
if (isPopupVisible()) {
int offset = 10 * item.getIndent();
this.setBorder(BorderFactory.createEmptyBorder(0, offset, 0, 0));
}
}
return this;
}
};
this.setRenderer(renderer);
}

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(400, 400);
Vector values = new Vector();
Icon openIcon = new ImageIcon(JImagedComboBox.class.getResource("Open16.gif"));
Icon newIcon = new ImageIcon(JImagedComboBox.class.getResource("New16.gif"));

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 长宁县| 蕲春县| 承德县| 大关县| 洛南县| 政和县| 黑水县| 肇东市| 保靖县| 沧州市| 宜丰县| 西贡区| 德清县| 芦山县| 富源县| 敖汉旗| 永兴县| 漳州市| 搜索| 淳化县| 乳山市| 平阳县| 增城市| 来安县| 太谷县| 新泰市| 安仁县| 剑川县| 安宁市| 榕江县| 平陆县| 牟定县| 钦州市| 中西区| 潼南县| 湘阴县| 科尔| 安国市| 鹤山市| 叶城县| 阿巴嘎旗|