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

📄 chap12-4.txt

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

public class testEventComboBox {
    JFrame  frame;
    Container  contentPane;
    JComboBox  imageComboBox;       // 下拉列表
    JLabel label,lll;               // 标签
    String questions[ ]={"姓名","性别","籍贯","学历"};  	// 问题数组
    String  answers[ ]={"皮德常","男","中国","博士"}; 	// 答案数组
    
    public testEventComboBox( ){     // 构造函数       
        frame=new subJFrame("testEventComboBox");     // 定义一个框架
        contentPane=frame.getContentPane( );	      // 获取框架的内容格
        contentPane.setLayout(new FlowLayout( ));    // 设置布局管理器
        
            // 依据questions数组生成一个下拉列表,并设置一屏可显示的项数
        imageComboBox=new JComboBox(questions); 	
        imageComboBox.setMaximumRowCount(3); 
        
        contentPane.add(imageComboBox);   // 将下拉列表加入内容格
        label=new JLabel(answers[0]);   	// 定义标签
        contentPane.add(label);     	 // 将标签加入内容格

            //注意:
            //下面是编写程序时一种很常用的方法:
        imageComboBox.addItemListener(

            // 生成一个无名内隐类,处理JComboBox事件
            new ItemListener( ){ 
                    // 处理JComboBox事件
                public void itemStateChanged(ItemEvent e) {     
                    if(e.getStateChange( )==ItemEvent.SELECTED){
                            // 确定选中的列表项下标,重新设置标签
                        int i=imageComboBox.getSelectedIndex( ); 
                        label.setText(answers[i]);  

                    }   // end of if
                }   // end of itemStateChanged
            }   // end of inner class 
        );  // end of ItemListener
        
        frame.setSize(300,150);
        frame.show( );
    } 
    
    public static void main(String args[ ]){
        testEventComboBox  obj=new testEventComboBox( );
    }
}

⌨️ 快捷键说明

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