Popular Posts
Add file to google drive using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v2; using Google.Apis.Drive.v2.Data; using Google.Apis.Services; using Google.Apis.Ut... Get file type icon path /// <summary> /// An item was added. /// </summary> public override void ItemAdded(SPItemEventProperties properties) {         v... ROBOCOPY: Robust File Copy for Windows -------------------------------------------------------------------------------    ROBOCOPY     ::     Robust File Copy for Windows --------...
Blog Archive
Stats
Limit input length of JTextField
package swixml.sample;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class LimitedTextField extends JFrame {

    public LimitedTextField() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Limit input length of JTextField");

        setLayout(new FlowLayout());

        // add a JTextField limit up to 10 chars
        add(new JTextField(new LimitedDocument(10), null, 20));

        pack();

        Dimension sc = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((sc.width - getWidth()) / 2, (sc.height - getHeight()) / 2);
        setVisible(true);
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        new LimitedTextField();
    }

}

class LimitedDocument extends PlainDocument {
    private int limit;

    public LimitedDocument(int limit) {
        super();
        this.limit = limit;
    }

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        if (limit == 0 || getLength() + str.length() <= limit) {
            super.insertString(offs, str, a);
        }
    }
}