3 下拉列表 JComboBox

下拉列表 JComboBox

一、基本用法

  1. 创建 JComboBox

    JComboBox<String> colorList = new JComboBox<>();
    
  2. 添加数据项

    colorList.addItem("红色");
    colorList.addItem("蓝色");
    colorList.addItem("绿色");
    

    addItem(T),T的类型在创建时指定,这里是String类型,也就说每一项Item的数据类型是 String

  3. 按索引访问

    getSelectedIndex();  //获取选中项的索引
    setSelectedIndex(int index);  //设置选中项
    removeItemAt(int index);  //按索引删除
    
  4. 按数据项访问

    getSelectedItem();
    setSelectedItem();
    removeItem();
    
  5. 事件处理
    还是ActionListener

代码:

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Demo {

	public static void main(String[] args) {
		MyFrame2 frame = new MyFrame2("Demo");
		frame.setSize(300, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
}

class MyFrame2 extends JFrame{
	JLabel label = new JLabel("一个案例,This is...");
	JComboBox<OptionList> comboBox = new JComboBox<>();
	
	public MyFrame2(String title) {
		super(title);
		
		Container contentPane = getContentPane();
		contentPane.setLayout(new FlowLayout());
		contentPane.add(comboBox);
		contentPane.add(label);
		
		comboBox.addItem(new OptionList("红色", Color.RED));
		comboBox.addItem(new OptionList("蓝色", Color.BLUE));
		comboBox.addItem(new OptionList("绿色", Color.GREEN));
		updateColor();
		
		comboBox.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				updateColor();
			}
		});
	}
	
	public void updateColor() {
		OptionList op = (OptionList)comboBox.getSelectedItem();
		label.setForeground(op.getColor());
	}
	
	private class OptionList {
		private String text;
		private Color color;
		
		public OptionList(String text, Color color) {
			this.text = text;
			this.color = color;
		}
		
		//重写toString方法,以便Swing进行展示
		public String toString() {
			return this.text;
		}

		public String getText() {
			return text;
		}

		public Color getColor() {
			return color;
		}
	}
}

输出:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值