Java如何将JTextField文本格式化为大写?
JTextField通过使用方法DocumentFilter向JTextField组件中添加a,可以轻松地将文本更改为大写setDocumentFilter()。该DocumentFilter让我们筛选器操作的文档中的更改,如插入,替换和删除。
下面的代码段向我们展示了如何实现。
package org.nhooo.example.swing; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.HeadlessException; public class DocumentFilterExample extends JFrame { public DocumentFilterExample() throws HeadlessException { initComponents(); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> new DocumentFilterExample().setVisible(true)); } protected void initComponents() { setSize(250, 250); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT)); JTextField firstName = new JTextField(); firstName.setPreferredSize(new Dimension(150, 20)); JTextField lastName = new JTextField(); lastName.setPreferredSize(new Dimension(150, 20)); DocumentFilter filter = new UppercaseDocumentFilter(); AbstractDocument firstNameDoc = (AbstractDocument) firstName.getDocument(); firstNameDoc.setDocumentFilter(filter); AbstractDocument lastNameDoc = (AbstractDocument) lastName.getDocument(); lastNameDoc.setDocumentFilter(filter); getContentPane().add(new JLabel("First Name: ")); getContentPane().add(firstName); getContentPane().add(new JLabel("Last Name: ")); getContentPane().add(lastName); } static class UppercaseDocumentFilter extends DocumentFilter { @Override public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException { fb.insertString(offset, text.toUpperCase(), attr); } @Override public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { fb.replace(offset, length, text.toUpperCase(), attrs); } } }