动态调整JTextField的大小并设置最小量的文本

时间:2012-12-22 02:24:10

标签: java swing jtextfield layout-manager

我想动态调整JTextField的大小,并设置允许的最小文本量。

实施例

文本字段的最小长度为4,如果文本小于4则为每个缺少的插槽添加0。

1 个答案:

答案 0 :(得分:0)

下面是一个这样的JTextField的例子:

public class TextField extends JTextField {
    public static final int TEXT_FIELD_PADDING = 4;

    public TextField() {
        addAutoResize();
        init();
    }

    public void init() {
        setStyleByParentStyle();
        this.setPreferredSize(new Dimension(Constant.
TEXT_FIELD_MINIMAL_WIDTH, this.getPreferredSize().height));
    }

    private void addAutoResize() {
        this.getDocument().addDocumentListener
(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
            checkResize();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
            checkResize();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
            checkResize();
            }
        });
    }

    private void checkResize() {
        FontMetrics fontMetrics = this.getFontMetrics(this.
getFont());

        if (fontMetrics.stringWidth(this.getText()) + 
TEXT_FIELD_PADDING * 2 < Constant.TEXT_FIELD_MINIMAL_WIDTH) {
            this.setPreferredSize(new 
Dimension(Constant.TEXT_FIELD_MINIMAL_WIDTH, this.getHeight()));
            this.getParent().revalidate();
        } else {
            //NOTE 2 - border width*2
            this.setPreferredSize(new 
Dimension(fontMetrics.stringWidth(this.getText()) + 2 + 
Constant.CARRET_WIDTH + TEXT_FIELD_PADDING * 2, this.getHeight()));
            this.getParent().revalidate();
        }
    }
}

此信息取自文章: Frequently Asked Questions during Java applet development