例如,如果输入的字符不是'x'
,有什么办法吗?还不如不采取任何行动。代码:
main_text_area.addKeyListener(new KeyListener()
{
public void keyTyped(KeyEvent e)
{
}
public void keyPressed(KeyEvent e1)
{
char c ='x';
if!((e1.getKeyChar() == c))
{
//Do nothing at all
}
}
public void keyReleased(KeyEvent e2)
{
}
最佳答案
最好不要在 Swing 文本组件中使用 KeyListener,因为这会干扰该组件的基本底层操作。此外,KeyListener 不会对通过任何其他方式(例如通过剪切和粘贴)添加或删除的文本产生任何影响。使用更高级别类型的监听器会更好。
例如,如果您希望收到任何文本更改的通知,无论是输入还是删除,那么您需要使用 DocumentListener,因为这会通知您文本的任何更改,无论是来自按键输入还是来自剪切和删除粘贴。
如果另一方面您想要过滤文本输入,甚至阻止某些文本输入,则将 DocumentFilter 附加到 JTextArea 的文档。
例如,您可以在 DocumentFilter 中放置一个 String#replaceAll(...)
来从字符串中删除所有非 X 字符。正则表达式 "[^xX]"
可以很好地解决此问题。
例如,
import javax.swing.*;
import javax.swing.text.PlainDocument;
@SuppressWarnings("serial")
public class DocFilterExample extends JPanel {
private static final int ROWS = 30;
private static final int COLS = 40;
private JTextArea textArea = new JTextArea(ROWS, COLS);
public DocFilterExample() {
((PlainDocument) textArea.getDocument()).setDocumentFilter(new XcharFilter());
add(new JScrollPane(textArea));
}
private static void createAndShowGui() {
JFrame frame = new JFrame("DocFilterExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DocFilterExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class XcharFilter extends DocumentFilter {
private static final String REGEX = "[^xX]";
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
throws BadLocationException {
string = string.replaceAll(REGEX, "");
super.insertString(fb, offset, string, attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
text = text.replaceAll(REGEX, "");
super.replace(fb, offset, length, text, attrs);
}
}
关于java - JTextArea 的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39852043/