栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将Map元素用作JComboBox的文本

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将Map元素用作JComboBox的文本

(2)指定这些对象在GUI中的显示方式。

您可以将任何Object添加到模型,然后创建一个自定义渲染器以任意方式显示该对象。显示toString()方法和自定义渲染器方法的简单示例:

import java.awt.*;import java.awt.event.*;import java.util.*;import javax.swing.*;import javax.swing.plaf.basic.*;public class ComboBoxItem extends Jframe implements ActionListener{    public ComboBoxItem()    {        Vector model = new Vector();        model.addElement( new Item(1, "car" ) );        model.addElement( new Item(2, "plane" ) );        model.addElement( new Item(3, "train" ) );        model.addElement( new Item(4, "boat" ) );        JComboBox comboBox;        //  Easiest approach is to just override toString() method        //  of the Item class        comboBox = new JComboBox( model );        comboBox.setDragEnabled(true);        comboBox.addActionListener( this );        getContentPane().add(comboBox, BorderLayout.NORTH );        //  Most flexible approach is to create a custom render        //  to diplay the Item data        comboBox = new JComboBox( model );        comboBox.setDragEnabled(true);        comboBox.setRenderer( new ItemRenderer() );        comboBox.addActionListener( this );        getContentPane().add(comboBox, BorderLayout.SOUTH );    }    public void actionPerformed(ActionEvent e)    {        JComboBox comboBox = (JComboBox)e.getSource();        Item item = (Item)comboBox.getSelectedItem();        System.out.println( item.getId() + " : " + item.getDescription() );    }    class ItemRenderer extends BasicComboBoxRenderer    {        public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)        { super.getListCellRendererComponent(list, value, index,     isSelected, cellHasFocus); if (value != null) {     Item item = (Item)value;     setText( item.getDescription().toUpperCase() ); } if (index == -1) {     Item item = (Item)value;     setText( "" + item.getId() ); } return this;        }    }    class Item    {        private int id;        private String description;        public Item(int id, String description)        { this.id = id; this.description = description;        }        public int getId()        { return id;        }        public String getDescription()        { return description;        }        public String toString()        { return description;        }    }    public static void main(String[] args)    {        Jframe frame = new ComboBoxItem();        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );        frame.pack();        frame.setVisible( true );     }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/609439.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号