[英]Adding a character while user enters value
當用戶填寫一定數量的字符時,如何創建一種自動添加字符的方法。
假設我必須輸入12個字符長的代碼。
每次我通過第四個字符時,都必須添加破折號。 (4-5,8-9)共2個破折號。
我對Java有點陌生,所以我不知道從哪里開始。
提前致謝。
使用JFormattedTextField
可以為其定義輸入掩碼
JFormattedTextField textField = new JFormattedTextField();
textField.setFormatterFactory(new DefaultFormatterFactory(new MaskFormatter("HHHH-HHHH-HHHH")));
編輯添加工作示例
public class SimpleInputMask {
private static void createAndShowGUI() {
JFrame frame = new JFrame("MaskFormatteExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JLabel label = new JLabel("input: ");
panel.add(label);
// define the text field with an input mask
JFormattedTextField textField = new JFormattedTextField();
textField.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
try {
String inputMask = "HHHH-HHHH-HHHH";
textField.setFormatterFactory(new DefaultFormatterFactory(new MaskFormatter(inputMask)));
} catch (ParseException ex) {
// will be raised if the inputMask cannot be parsed
// add your own exception handling here
}
panel.add(textField);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.