重写JTextField控件,控制JTextField长度和只能在JTextField中输入数字

窗口显示类

package filechooser;

import java.io.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.filechooser.*;

/*
 * FileChooserDemo.java uses these files:
 *   images/Open16.gif
 *   images/Save16.gif
 */
public class FileChooserDemo extends JPanel
                             implements ActionListener {
    static private final String newline = "/n";
    JButton openButton, saveButton;
    JTextArea log;
    JFileChooser fc;
    UpperCaseField upper;
   
    UpperCaseField upperField;

    public FileChooserDemo() {
        super(new BorderLayout());

        log = new JTextArea(5,20);
        log.setMargin(new Insets(5,5,5,5));
        log.setEditable(false);
        JScrollPane logScrollPane = new JScrollPane(log);

        fc = new JFileChooser();

        openButton = new JButton("Open a File...",
                                 createImageIcon("images/Open16.gif"));
        openButton.addActionListener(this);

        saveButton = new JButton("Save a File...",
                                 createImageIcon("images/Save16.gif"));
        saveButton.addActionListener(this);
       
        JPanel buttonPanel = new JPanel(); //use FlowLayout
        buttonPanel.add(openButton);
        buttonPanel.add(saveButton);

        upper = new UpperCaseField(20,saveButton,4);
       
        upperField = new UpperCaseField(10,saveButton,4);
       
        //增加文档事件
        upper.getDocument().addDocumentListener(new UpperDocumentListener(upper));
        upperField.getDocument().addDocumentListener(new UpperDocumentListener(upperField));
        buttonPanel.add(upperField);
        add(upper,BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.PAGE_START);
        //add(logScrollPane, BorderLayout.CENTER);
    }

    public void actionPerformed(ActionEvent e) {

     if (e.getSource() == openButton) {
//            int returnVal = fc.showOpenDialog(FileChooserDemo.this);
//
//            if (returnVal == JFileChooser.APPROVE_OPTION) {
//                File file = fc.getSelectedFile();
//
//                log.append("Opening: " + file.getName() + "." + newline);
//            } else {
//                log.append("Open command cancelled by user." + newline);
//            }
//            log.setCaretPosition(log.getDocument().getLength());
      if(upper.tempPass.length()>10)
      {
       System.out.println("temp : ["+upper.tempPass.substring(0,10)+"]");
      }
      else
      {
       System.out.println("temp : ["+upper.tempPass+"]");
      }

        } else if (e.getSource() == saveButton) {
            int returnVal = fc.showSaveDialog(FileChooserDemo.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();

                log.append("Saving: " + file.getName() + "." + newline);
            } else {
                log.append("Save command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());
        }
    }

    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = FileChooserDemo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("FileChooserDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(new FileChooserDemo());

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
         SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                 UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
    }
}

重写JTextField控件类

package filechooser;

import java.awt.TextField;

import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

public class UpperCaseField extends JTextField {
 public String temp = "";
 
 public int cols = 0;
 
 public String tempPass = "";
 
 public JButton jButton;
 
 public int size;

 public UpperCaseField(int cols,JButton jButton,int size) {
  super(cols);
  this.cols = cols;
  this.jButton = jButton;
  this.size = size;
 }

 protected Document createDefaultModel() {
  return new UpperCaseDocument();
 }

 class UpperCaseDocument extends PlainDocument {
  
  public void insertString(int offs, String str, AttributeSet a)
    throws BadLocationException {
   String tempInput = "";
   
   
   System.out.println("temp : ["+str.matches("^[^0-9]+$")+"]");
   if(str.matches("^[^0-9]+$"))
   {
    return;
   }
   
   temp += str;
   
   if (temp.length() > cols) {
    return;
   }
   
   tempPass += str;
   
   for(int i=0;i<str.length();i++)
   {
    tempInput +="*";
   }
   
   if(tempPass.length() >= size)
   {
    jButton.setEnabled(false);
   }

   super.insertString(offs, tempInput, a);
  }
 }
}

重写DocumentListener事件类

package filechooser;

import javax.swing.JPanel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;

public class UpperDocumentListener implements DocumentListener{

 protected UpperCaseField upperField;
 
 public UpperDocumentListener(UpperCaseField upperField)
 {
  this.upperField = (UpperCaseField)upperField;
 }
 public void changedUpdate(DocumentEvent e) {
   try {
    this.upperField.temp = e.getDocument().getText(0, e.getDocument().getLength());
   } catch (BadLocationException e1) {
    e1.printStackTrace();
   }
 }

 public void insertUpdate(DocumentEvent e) {
   try {
    this.upperField.temp = e.getDocument().getText(0, e.getDocument().getLength());
   } catch (BadLocationException e1) {
    e1.printStackTrace();
   }
 }

 public void removeUpdate(DocumentEvent e) {
   try {
    this.upperField.tempPass = this.upperField.tempPass.substring(0,e.getDocument().getLength());
    
    if(this.upperField.tempPass.length() < this.upperField.size)
    {
     this.upperField.jButton.setEnabled(true);
    }
    this.upperField.temp = e.getDocument().getText(0, e.getDocument().getLength());
   } catch (BadLocationException e1) {
    e1.printStackTrace();
   }
 }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值