问题描述
所以我想将所有输入的字符自动转换为大写.
So I want to automatically convert all entered characters to uppercase.
这是代码的相关部分:
editorPane = new JEditorPane();
editorPane.getCaret().setBlinkRate(0);
this.keyListener = new UIKeyListener(editorPane);
editorPane.addKeyListener(keyListener);
而 UIKeyListener 类我只提供 keyReleased 函数,因为其他部分只是样板代码
And the UIKeyListener Class I am only providing the keyReleased function as other part is just boilerplate code
@Override
public void keyReleased(KeyEvent e) {
capitalizeCode();
}
private void capitalize() {
int prevCarerPosition = editorPane.getCaretPosition();
editorPane.setText(editorPane.getText().toUpperCase());
editorPane.setCaretPosition(prevCarerPosition);
}
这基本上没问题,但问题是:-
This is mostly OK but the problems are :-
- 我无法选择文本
- 每次我输入字符时,它们首先以小写字母出现,然后变成大写字母
现在,如果我从 keyTyped 函数调用大写函数,第一个问题就解决了,但有一个新问题:最后输入的字母仍然很小
Now The first problem is solved if I call the capitalize function from keyTyped function but there there is a new problem : the last typed letter remains small
而且我还想问一下,我们是否可以在不听键事件的情况下执行此操作,例如默认情况下编辑器窗格只接受大写字母?
And I also want to ask whether can we do this without listening to keyevents like by default the editorpane will only accept capital letters?
推荐答案
不要使用 KeyListener.
Don't use a KeyListener.
更好的方法是使用 DocumentFilter
.
无论文本是键入还是粘贴到文本组件中,这都将起作用.
This will work whether text is typed or pasted into the text component.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class UpperCaseFilter extends DocumentFilter
{
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
throws BadLocationException
{
replace(fb, offs, 0, str, a);
}
public void replace(FilterBypass fb, final int offs, final int length, final String text, final AttributeSet a)
throws BadLocationException
{
if (text != null)
{
super.replace(fb, offs, length, text.toUpperCase(), a);
}
}
private static void createAndShowGUI()
{
JTextField textField = new JTextField(10);
AbstractDocument doc = (AbstractDocument) textField.getDocument();
doc.setDocumentFilter( new UpperCaseFilter() );
JFrame frame = new JFrame("Upper Case Filter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout( new java.awt.GridBagLayout() );
frame.add( textField );
frame.setSize(220, 200);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
EventQueue.invokeLater( () -> createAndShowGUI() );
}
}
过滤器可用于任何文本组件.
The filter can be used on any text component.
请参阅 Swing 教程中关于实施文档过滤器的部分 了解更多信息.
See the section from the Swing tutorial on Implementing a DocumentFilter for more information.
这篇关于如何在 Java JEditorPane 中自动将小写字母更新为大写字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!