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

📄 chap12-2.txt

📁 JAVA 学习资源
💻 TXT
字号:
// 程序12-2
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class testEventField {	// 主类
    JFrame  frame;
    Container  contentPane;
    JTextField  field1,field2,field3;
    JPasswordField  password;
    JLabel  label;
    
	// 此类为了响应文本事件处理,实现了ActionListener接口
    private class fieldEventHandler implements ActionListener{ 	// 内隐类
        public void actionPerformed(ActionEvent e) {
            String str="";
        
	// 判断用户是否在field1文本框中按了Enter键
            if(e.getSource( )==field1)	// 通过getSource( )获取事件
                str="field1 : "+e.getActionCommand( );
            else if(e.getSource( )==field2)
                str="field2 : "+e.getActionCommand( );
            else if(e.getSource( )==field3)
                str="field3 : "+e.getActionCommand( );
            else if(e.getSource( )==password)	// 获取JPasswordField文本
                str="password : "+e.getActionCommand( ); 
            label.setText(str);	   // 采用标签显示获取的文本信息
        }        
    }
    
    public testEventField( ){    
        frame=new subJFrame("testEventField");
        contentPane=frame.getContentPane( );          
        contentPane.setLayout(new GridLayout(2,3,10,10)); 	// 设置内容格的布局

          // 生成3个文本框
        field1=new JTextField(10);  	// 文本框的宽度为10
        field2=new JTextField("Enter text here");   	// 具有默认文本 
        field3=new JTextField("Uneditable this text",20);       
        field3.setEditable(false); 
        
        password=new JPasswordField("Hide this text",20); 	// 生成一个口令文本框
        
          // 生成一个没有显示文本的标签
        label=new JLabel("I am a label");       	
        contentPane.add(label);

          // 将四个文本对象加入到内容格
        contentPane.add(field1);     
        contentPane.add(field2);
        contentPane.add(field3);
        contentPane.add(password);

          // 生成一个监听者,并将其注册为4个文本对象的监听者
        fieldEventHandler handler=new fieldEventHandler( );
        field1.addActionListener(handler);
        field2.addActionListener(handler);
        field3.addActionListener(handler);
        password.addActionListener(handler);
        
        frame.setSize(400,100);
        frame.show( );
    } 
    
    public static void main(String args[ ]){
        testEventField  obj=new testEventField( );
    }
}

⌨️ 快捷键说明

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