gpt4 book ai didi

java 强制 JTextField 仅大写

转载 作者:搜寻专家 更新时间:2023-11-01 04:00:44 26 4
gpt4 key购买 nike

有没有办法在 Java 中强制所有用户在 JTextField 中输入大写?

最佳答案

一个完整的工作示例可能对您有所帮助

import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class UpperCasedTextFieldTester extends JFrame {
/** */
private static final long serialVersionUID = -4767854098431909437L;

public UpperCasedTextFieldTester(){
setSize(200, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));

DocumentFilter filter = new UppercaseDocumentFilter();

JTextField firstName = new JTextField();
firstName.setPreferredSize(new Dimension(100, 20));
((AbstractDocument) firstName.getDocument()).setDocumentFilter(filter);

JTextField lastName = new JTextField();
lastName.setPreferredSize(new Dimension(100, 20));
((AbstractDocument) lastName.getDocument()).setDocumentFilter(filter);

add(firstName);
add(lastName);
}

public static void main(String[] args) {
new UpperCasedTextFieldTester().setVisible(true);
}

}

class UppercaseDocumentFilter extends DocumentFilter {
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String text, AttributeSet attr) throws BadLocationException {

fb.insertString(offset, text.toUpperCase(), attr);
}

public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {

fb.replace(offset, length, text.toUpperCase(), attrs);
}
}

关于java 强制 JTextField 仅大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11571779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com