⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chap12-5.txt

📁 清华大学出版社经典教材系列
💻 TXT
字号:
// 程序12-5
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;

public class testEventList {
    JFrame  frame;
    Container  contentPane;
    JList  list;    // 下拉列表
    JLabel label;   // 标签
        // 下面定义了颜色数组和相应的颜色对象数组
    String colorNames[ ]={" Black"," Blue "," Red "," White","Yellow"};  
    Color  colors[ ]={Color.black,Color.blue,Color.red,Color.white,Color.yellow}; 
    
    public testEventList( ){               	// 构造函数        
        frame=new subJFrame("testEventList");  	// 定义一个框架
        contentPane=frame.getContentPane( );	// 获取框架的内容格
        contentPane.setLayout(new FlowLayout( ));	// 设置布局管理器 

        list=new JList(colorNames);      // 依据数组生成列表
        list.setVisibleRowCount(4);      // 设置列表一次显示的项数

	    // 设置选择模式,一次只能选择一条
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 

	    // 生成一个滚动面板,并将下拉列表加入滚动面板
        contentPane.add(new JScrollPane(list)); 
        
        label=new JLabel(" 颜色 ");    // 定义标签
        contentPane.add(label);         // 将标签加入内容格 

        list.addListSelectionListener(

                // 生成一个匿名类对象,处理JList事件
            new ListSelectionListener( ) {  // 下面是匿名类的定义
                    // 匿名类中只有一个方法,处理JList选择项改变事件
                public void valueChanged(ListSelectionEvent e) { 
                    label.setText(list.getSelectedValue( ).toString( ));                  
                    label.setForeground(colors[list.getSelectedIndex( )]);
                }   // end of valueChanged
            }  // end of inner class        

        );  // end of addListSelectionListener
        
        frame.setSize(200,120);
        frame.show( );
    } 
    
    public static void main(String args[ ]){
        testEventList  obj=new testEventList( );
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -