Liny_@NotePad

沉迷ACG中

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

YOYO posted @ 2009年8月21日 06:34 in 【Java SE】 with tags 重置 Swing , 6747 阅读

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

  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. * <p>Title: 重置按钮监听器</p>
  13. *
  14. * <p>Description: 单击重置按钮 清空窗体中数据</p>
  15. *
  16. * @author YOYO
  17. *
  18. * @create 2009-8-8
  19. *
  20. * @修改历史
  21. * <li>版本号 修改日期 修改人 修改说明
  22. * <li>
  23. * <li>
  24. */
  25. public class SuperResetButtonAction implements ActionListener {
  26.        
  27.         private Container container;
  28.        
  29.         public SuperResetButtonAction(Container container) {
  30.                 this.container = container;
  31.         }
  32.        
  33.         /**
  34.          * 清空容器内容
  35.          * @param parent
  36.          */
  37.         private void clear(Container parent) {
  38.                 for(Component component: parent.getComponents()){
  39.                         if(component instanceof Container) {
  40.                                 clear((Container) component);
  41.                         }
  42.                         if(component instanceof JTextField) {
  43.                                 ((JTextField) component).setText("");
  44.                         }
  45.                         if(component instanceof JTextArea) {
  46.                                 ((JTextArea) component).setText("");
  47.                         }
  48.                         if(component instanceof JComboBox) {
  49.                                 if(((JComboBox) component).getItemCount()>0) {
  50.                                         ((JComboBox) component).setSelectedIndex(0);
  51.                                 }
  52.                         }
  53.                         if(component instanceof JList) {
  54.                                 ((JList)component).clearSelection();
  55.                         }
  56.                 }
  57.         }
  58.  
  59.         public void actionPerformed(ActionEvent arg0) {
  60.                 clear(container);
  61.         }
  62.  
  63. }

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter