我有JTextArea组件,我需要禁用用户修改\删除组件中当前的内容。用户只能在末尾添加\insert一些文本,但是setText方法必须像往常一样工作。
tnx
发布于 2014-01-20 07:15:45
你能举个例子说明一下你已经有了什么吗?
为了澄清,如果您希望用户无法处理某些事情,您可能需要手动重新插入原始文本。我不确定JTextArea所使用的编辑器,但您可以尝试重写它。
我当场想出了可怕的代码,您可能可以更容易地做到这一点:
private static String mand = "mandatory.";
private static JTextArea test = new JTextArea(mand);
public static String getMand() {
return mand;
}
public static JTextArea getTest() {
return test;
}
public static void setMand(String mand2) {
mand = mand2;
}
public static void setTest(JTextArea test2) {
test = test2;
}
getTest().addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent arg0) {
// do nothing
}
@Override
public void keyReleased(KeyEvent arg0) {
// do nothing
}
@Override
public void keyTyped(KeyEvent arg0) {
if(getTest().getText().startsWith(getMand())) {
System.out.println("good, text still present");
setMand(test.getText());
} else {
getTest().setText(getMand());
}
}
});
警告 ::如果用户在向JTextArea
添加信息时出错,代码将不允许用户修复这些错误。
在JDK (/JRE) 7下测试成功。
发布于 2014-01-20 09:22:00
我需要禁用用户修改\删除组件中的当前内容。
textArea.setEditable( false );
用户只能在末尾添加\insert一些文本,但是setText方法必须像往常一样工作。
您应该有一个"Add“按钮,它将从一个单独的文本字段获取文本,然后使用append(...)
的JTextArea方法将文本附加到文档中。
https://stackoverflow.com/questions/21236968
复制相似问题