我想动态调整JTextField
的大小,并设置允许的最小文本量。
文本字段的最小长度为4,如果文本小于4则为每个缺少的插槽添加0。
答案 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