有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (4) 个答案

  1. # 1 楼答案

    Customized fields can easily be created by extending the model and changing the default model provided. For example, the following piece of code will create a field that holds only upper case characters. It will work even if text is pasted into from the clipboard or it is altered via programmatic changes.

     public class UpperCaseField extends JTextField {
    
         public UpperCaseField(int cols) {
             super(cols);
         }
    
         protected Document createDefaultModel() {
             return new UpperCaseDocument();
         }
    
         static class UpperCaseDocument extends PlainDocument {
    
             public void insertString(int offs, String str, AttributeSet a)
                 throws BadLocationException {
    
                 if (str == null) {
                     return;
                 }
                 char[] upper = str.toCharArray();
                 for (int i = 0; i < upper.length; i++) {
                     upper[i] = Character.toUpperCase(upper[i]);
                 }
                 super.insertString(offs, new String(upper), a);
             }
         }
     }
    

    提供:JTextField

  2. # 2 楼答案

    试一试

    jtextfield.addKeyListener(new KeyAdapter(){
       keyReleased(KeyEvent e) {
          jtextfield.setText(jtextfield.getText().toUpperCase());
       }
    
    });
    
  3. # 4 楼答案

    定义一个DocumentFilter并分配给JTextFiledDocument或只是扩展JTextField中使用的PlainDocument并重写insertString()方法。将字符串参数转换为大写并传递给super.insertString()