Java JTextfield在键入时动态添加文本
我有一个“格式化”字段——也就是说,它最终必须是这样的格式:xx/xxxx/xx 我想让它在键入时自动添加“/” 我试图拼凑的方式是这样的:Java JTextfield在键入时动态添加文本,java,swing,jtextfield,Java,Swing,Jtextfield,我有一个“格式化”字段——也就是说,它最终必须是这样的格式:xx/xxxx/xx 我想让它在键入时自动添加“/” 我试图拼凑的方式是这样的: JTextField field = new JTextField ("xx/xxxx/xx"); // a focus listener to clear the "xx/xxxx/xx" on focus & restore on focus-out // the override the 'document' with this: fiel
JTextField field = new JTextField ("xx/xxxx/xx");
// a focus listener to clear the "xx/xxxx/xx" on focus & restore on focus-out
// the override the 'document' with this:
field.setDocument (new PlainDocument () {
public void insertString (int off, String str, AttributeSet attr) throws BadLocationException {
if (off == 2 || off == 7) {
super.insertString (off + 1, str + "/", attr);
}
}
}
这似乎是要打破-我该如何正确处理它从:xx/xx。。到xx?我认为让他们删除“/”是可以的
我觉得应该有更好的办法?也许我可以用一个图书馆?除了我的…特别的东西
谢谢你的任何意见 Hmm您可以使用
JFormattedTextField
看看下面的示例,这将创建一个JFormattedTextField
,它将只接受数字,并将它们放在XX/XXXX/XX格式中:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.text.MaskFormatter;
public class FormattedTextFieldExample extends JFrame {
public FormattedTextFieldExample() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(200, 200));
getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
MaskFormatter mask = null;
try {
//
// Create a MaskFormatter for accepting phone number, the # symbol accept
// only a number. We can also set the empty value with a place holder
// character.
//
mask = new MaskFormatter("##/####/##");
mask.setPlaceholderCharacter('_');
} catch (ParseException e) {
e.printStackTrace();
}
//
// Create a formatted text field that accept a valid phone number.
//
JFormattedTextField phoneField = new JFormattedTextField(mask);
phoneField.setPreferredSize(new Dimension(100, 20));
getContentPane().add(phoneField);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FormattedTextFieldExample().setVisible(true);
}
});
}
}
参考:
JFormattedTextField
看看下面的示例,这将创建一个JFormattedTextField
,它将只接受数字,并将它们放在XX/XXXX/XX格式中:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.text.MaskFormatter;
public class FormattedTextFieldExample extends JFrame {
public FormattedTextFieldExample() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(200, 200));
getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
MaskFormatter mask = null;
try {
//
// Create a MaskFormatter for accepting phone number, the # symbol accept
// only a number. We can also set the empty value with a place holder
// character.
//
mask = new MaskFormatter("##/####/##");
mask.setPlaceholderCharacter('_');
} catch (ParseException e) {
e.printStackTrace();
}
//
// Create a formatted text field that accept a valid phone number.
//
JFormattedTextField phoneField = new JFormattedTextField(mask);
phoneField.setPreferredSize(new Dimension(100, 20));
getContentPane().add(phoneField);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FormattedTextFieldExample().setVisible(true);
}
});
}
}
参考:
- 为了实现这一点,我做了以下几点:
JTextField field = new JTextField ();
field.setDocument (new PlainDocument () {
public void insertString (int off, String str, AttributeSet attr) throws BadLocationException {
if (off < 10) { // max size clause
if (off == 1 || off == 6) { // insert the '/' occasionally
str = str + "/";
}
super.insertString (off, str, attr);
}
}
});
field.setText ("xx/xxxx/xx"); // set AFTER otherwise default won't show up!
field.setForeground (ColorConstants.DARK_GRAY_080); // make it light!
field.addFocusListener (new ClearingFocusListener (field)); // could be done in an anonymous inner class - but I use it other places
private static class ClearingFocusListener implements FocusListener {
final private String initialText;
final private JTextField field;
public ClearingFocusListener (final JTextField field) {
this.initialText = field.getText ();
this.field = field;
}
@Override
public void focusGained (FocusEvent e) {
if (initialText.equals (field.getText ())) {
field.setText ("");
field.setForeground (ColorConstants.DARK_GRAY_080);
}
}
@Override
public void focusLost (FocusEvent e) {
if ("".equals (field.getText ())) {
field.setText (initialText);
field.setForeground (ColorConstants.LIGHT_GRAY_220);
}
}
}
JTextField=newjtextfield();
field.setDocument(新的PlainDocument(){
public void insertString(int off、String str、AttributeSet attr)引发BadLocationException{
if(off<10){//max size子句
如果(off==1 | | off==6){//偶尔插入“/”
str=str+“/”;
}
super.insertString(关闭、str、attr);
}
}
});
field.setText(“xx/xxxx/xx”);//设置后,否则默认值将不会显示!
field.set前台(ColorConstants.DARK_GRAY_080);//轻一点!
field.addFocusListener(新的ClearingFocusListener(字段));//可以在匿名内部类中完成,但我在其他地方使用它
私有静态类ClearingFocusListener实现FocusListener{
最后一个私有字符串initialText;
最终私有JTextField字段;
公共ClearingFocusListener(最终JTextField){
this.initialText=field.getText();
this.field=字段;
}
@凌驾
获得公共无效焦点(焦点事件e){
if(initialText.equals(field.getText())){
field.setText(“”);
field.setForeground(颜色常数.DARK\u GRAY\u 080);
}
}
@凌驾
公共无效焦点丢失(焦点事件e){
如果(“.”等于(field.getText()){
field.setText(initialText);
field.setForeground(颜色常数.浅灰色220);
}
}
}
这与另一种解决方案不同,因为当没有文本时,“/”不存在,而是添加到正确的位置。它目前不处理任何替代品——呃。:/ 为了实现这一点,我做了以下工作:
JTextField field = new JTextField ();
field.setDocument (new PlainDocument () {
public void insertString (int off, String str, AttributeSet attr) throws BadLocationException {
if (off < 10) { // max size clause
if (off == 1 || off == 6) { // insert the '/' occasionally
str = str + "/";
}
super.insertString (off, str, attr);
}
}
});
field.setText ("xx/xxxx/xx"); // set AFTER otherwise default won't show up!
field.setForeground (ColorConstants.DARK_GRAY_080); // make it light!
field.addFocusListener (new ClearingFocusListener (field)); // could be done in an anonymous inner class - but I use it other places
private static class ClearingFocusListener implements FocusListener {
final private String initialText;
final private JTextField field;
public ClearingFocusListener (final JTextField field) {
this.initialText = field.getText ();
this.field = field;
}
@Override
public void focusGained (FocusEvent e) {
if (initialText.equals (field.getText ())) {
field.setText ("");
field.setForeground (ColorConstants.DARK_GRAY_080);
}
}
@Override
public void focusLost (FocusEvent e) {
if ("".equals (field.getText ())) {
field.setText (initialText);
field.setForeground (ColorConstants.LIGHT_GRAY_220);
}
}
}
JTextField=newjtextfield();
field.setDocument(新的PlainDocument(){
public void insertString(int off、String str、AttributeSet attr)引发BadLocationException{
if(off<10){//max size子句
如果(off==1 | | off==6){//偶尔插入“/”
str=str+“/”;
}
super.insertString(关闭、str、attr);
}
}
});
field.setText(“xx/xxxx/xx”);//设置后,否则默认值将不会显示!
field.set前台(ColorConstants.DARK_GRAY_080);//轻一点!
field.addFocusListener(新的ClearingFocusListener(字段));//可以在匿名内部类中完成,但我在其他地方使用它
私有静态类ClearingFocusListener实现FocusListener{
最后一个私有字符串initialText;
最终私有JTextField字段;
公共ClearingFocusListener(最终JTextField){
this.initialText=field.getText();
this.field=字段;
}
@凌驾
获得公共无效焦点(焦点事件e){
if(initialText.equals(field.getText())){
field.setText(“”);
field.setForeground(颜色常数.DARK\u GRAY\u 080);
}
}
@凌驾
公共无效焦点丢失(焦点事件e){
如果(“.”等于(field.getText()){
field.setText(initialText);
field.setForeground(颜色常数.浅灰色220);
}
}
}
这与另一种解决方案不同,因为当没有文本时,“/”不存在,而是添加到正确的位置。它目前不处理任何替代品——呃。:/ 这不是只有在用户退出该字段时才会执行吗?他们打字的时候我正在试着做(我在看)@thelonesquirry嗯,你试过了吗?不,不会的。使用
JFormattedTextField
时已插入掩码,抱歉!当我读到这篇文章时,我并没有站在我的开发机器前,它工作得非常出色。我在寻找一些看起来更“网络化”的东西,因为它没有永久性的“/”。更多的是一种风格,而不是功能。虽然我错过了格式化文本编辑器的一些功能,但永远不要使用setXXSize(请参阅),不过,格式化文本字段和maskFormatter:-)的+1不是只有在用户退出该字段时才会使用吗?他们打字的时候我正在试着做(我在看)@thelonesquirry嗯,你试过了吗?不,不会的。使用JFormattedTextField
时已插入掩码,抱歉!当我读到这篇文章时,我并没有站在我的开发机器前,它工作得非常出色。我在寻找一些看起来更“网络化”的东西,因为它没有永久性的“/”。更多的是一种风格,而不是功能。尽管我错过了格式化文本编辑器的一些功能,但永远不要使用setXXSize(请参阅),格式化文本字段和maskFormatter的+1:-)