有没有办法强制JTextField
中的所有用户输入在Java中为大写?
答案 0 :(得分:10)
完整的工作示例可以帮助您
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);
}
}
答案 1 :(得分:6)
您有两个即时选择。您可以提供自己的document,这只是一点点工作,或者提供您自己的DocumentFilter
或者,您只是谷歌并查看您找到的内容,例如http://www.java2s.com/Code/Java/Swing-JFC/DocumentFilterthatmapslowercaseletterstouppercase.htm这个;)
答案 2 :(得分:3)
以下是DocumentFilter
的示例。
AbstractDocument document = (AbstractDocument) textfield
.getDocument();
document.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset,
String string, AttributeSet attr)
throws BadLocationException {
super.insertString(fb, offset, string.toUpperCase(), attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs)
throws BadLocationException {
super.insertString(fb, offset, text.toUpperCase(), attrs);
}
});