gpt4 book ai didi

java - 使用 KeyEvent(KeyPressed、KeyTyped 等)将字符附加到 JTextArea

转载 作者:行者123 更新时间:2023-12-01 18:35:44 27 4
gpt4 key购买 nike

当我在按下特定按钮后尝试将字符或字符串附加到 jtextarea 时,会发生一些奇怪的事情,例如我想在 jtextarea 中按用户按“{”后附加“}”,通过以下代码,最终jTextArea 中的字符串将是“}{”而不是“{}”

private void keyPressedEvent(java.awt.event.KeyEvent evt)
{
if(evt.getkeychar() == '{' )
{
JtextArea1.append("}");
}
}

最佳答案

您几乎不应该在 JTextArea 或其他 JTextComponent 上使用 KeyListener。为此,我将使用 DocumentFilter,它允许您在用户输入发送到文档之前更新文档。

例如,

import javax.swing.*;
import javax.swing.text.*;

public class DocFilterEg {
public static void main(String[] args) {
JTextArea textArea = new JTextArea(10, 20);
PlainDocument doc = (PlainDocument) textArea.getDocument();
doc.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset, String text,
AttributeSet attr) throws BadLocationException {
text = checkTextForParenthesis(text);
super.insertString(fb, offset, text, attr);
}

@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) throws BadLocationException {
text = checkTextForParenthesis(text);
super.replace(fb, offset, length, text, attrs);
}

private String checkTextForParenthesis(String text) {
if (text.contains("{") && !text.contains("}")) {
int index = text.indexOf("{") + 1;
text = text.substring(0, index) + "}" + text.substring(index);
}
return text;
}
});
JOptionPane.showMessageDialog(null, new JScrollPane(textArea));
}
}

关于java - 使用 KeyEvent(KeyPressed、KeyTyped 等)将字符附加到 JTextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22120698/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com