Popular Posts
SwiXml - Layout BorderLayout BorderLayoutPane.xml <?xml version="1.0" encoding="UTF-8"?> <panel layout="BorderLayout... DNS SERVER LIST Google 8.8.8.8 8.8.4.4 TWNIC 192.83.166.11 211.72.210.250 HiNet 168.95.1.1 168.95.192.1 Seednet 北區 DNS (台北, 桃園, 新竹, 宜蘭, 花蓮, 苗栗) 139.... Enable SSL connection for Jsoup import org.jsoup.Connection; import org.jsoup.Jsoup; import javax.net.ssl.*; import java.io.IOException; import java.security.KeyManagement...
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);
        }
    }
}