Swing:重置按钮的监听器实现

本文介绍了一种实现重置按钮功能的方法,通过监听器递归遍历容器内的组件并清空文本框、文本区域等输入组件的内容,同时将下拉菜单重置为默认选项并清除列表的选择。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

rt。。写了一个类实现ActionListener,actionPerformed时递归遍历容器中的所有组件 如果是可输入组件则清除内容,可选择组件则清除选择。

Code:
  1. import java.awt.Component;   
  2. import java.awt.Container;   
  3. import java.awt.event.ActionEvent;   
  4. import java.awt.event.ActionListener;   
  5.     
  6. import javax.swing.JComboBox;   
  7. import javax.swing.JList;   
  8. import javax.swing.JTextArea;   
  9. import javax.swing.JTextField;   
  10.     
  11. /**  
  12. Title: 重置按钮监听器

     
  13.  
  14. Description: 单击重置按钮 清空窗体中数据

     
  15.  
  16. * @author YOYO  
  17.  
  18. * @create 2009-8-8  
  19.  
  20. * @修改历史  
    • 版本号 修改日期 修改人 修改说明
     
     
     
  21. */  
  22. public class SuperResetButtonAction implements ActionListener {   
  23.           
  24.         private Container container;   
  25.           
  26.         public SuperResetButtonAction(Container container) {   
  27.                 this.container = container;   
  28.         }   
  29.           
  30.         /**  
  31.          * 清空容器内容  
  32.          * @param parent  
  33.          */  
  34.         private void clear(Container parent) {   
  35.                 for(Component component: parent.getComponents()){   
  36.                         if(component instanceof Container) {   
  37.                                 clear((Container) component);   
  38.                         }   
  39.                         if(component instanceof JTextField) {   
  40.                                 ((JTextField) component).setText("");   
  41.                         }   
  42.                         if(component instanceof JTextArea) {   
  43.                                 ((JTextArea) component).setText("");   
  44.                         }   
  45.                         if(component instanceof JComboBox) {   
  46.                                 if(((JComboBox) component).getItemCount()>0) {   
  47.                                         ((JComboBox) component).setSelectedIndex(0);   
  48.                                 }   
  49.                         }   
  50.                         if(component instanceof JList) {   
  51.                                 ((JList)component).clearSelection();   
  52.                         }   
  53.                 }   
  54.         }   
  55.     
  56.         public void actionPerformed(ActionEvent arg0) {   
  57.                 clear(container);   
  58.         }   
  59.     
  60. }  

 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值