我想限制JTextField
仅输入数字,但是我可以通过setText
函数将文本设置为非数字。
因为我想提示JTextField
中没有字符。
这就是我想要的效果:当JTextField没有获得焦点时,它会显示一个提示文本。
这是我的代码
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
public class InputFieldFrame extends JFrame implements FocusListener {
public static void main(String[] args) {
new InputFieldFrame();
}
JTextField input = new JTextField(12);
public InputFieldFrame() {
//input.setDocument(new NumberFilter()); // Remove the comment can just enter the number, but the hint function will fail.
//input.setText("Hint Text"); // This will not take effect
input.addFocusListener(this);
add(input);
setSize(new Dimension(200, 200));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void focusGained(FocusEvent e) {
if (input.getText().equals("Hint"))
input.setText("");
}
@Override
public void focusLost(FocusEvent e) {
if (input.getText().equals(""))
input.setText("Hint");
}
class NumberFilter extends PlainDocument {
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
if (str.charAt(0) >= '0' && str.charAt(0) <= '9') {
System.out.println(str);
super.insertString(offs, str, a);
}
}
}
}