有没有办法强制所有用户输入JTextField
在 Java 中为大写?
问问题
17248 次
3 回答
11
一个完整的工作示例可能会对您有所帮助
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);
}
}
于 2012-07-20T05:19:42.647 回答
6
你有两个直接的选择。您可以提供自己的文档,这有点工作,或者提供自己的DocumentFilter
或者,您只需 google 并查看您找到的内容,例如http://www.java2s.com/Code/Java/Swing-JFC/DocumentFilterthatmapslowercaseletterstouppercase.htm ;)
于 2012-07-20T01:57:58.703 回答
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);
}
});
于 2012-07-20T02:23:28.760 回答