[英]key pressed how show message file read only in jpanel when text area is non editable?
When i open file in jtextarea. 当我在jtextarea中打开文件时。 I set to textarea to non editable by using textArea.setEditable(false) but in the when i press the key how to show the message in jpanel file is read only.
我通过使用textArea.setEditable(false)将textarea设置为不可编辑,但是在按键时,如何在jpanel文件中显示消息是只读的。
Thank you. 谢谢。
Don't use setEditable(false), use TextFilter instead: 不要使用setEditable(false),而应使用TextFilter:
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class TextAreaTest {
/**
*
* @param args
*/
public static void main(String[] args) {
final JFrame frm = new JFrame("Text field test");
final JTextArea area = new JTextArea("Some text here", 20, 50);
((AbstractDocument) area.getDocument()).setDocumentFilter(new DocumentFilter() {
/**
* {@inheritDoc}
*/
@Override
public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
JOptionPane.showMessageDialog(frm, "Area read only");
}
/**
* {@inheritDoc}
*/
@Override
public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
JOptionPane.showMessageDialog(frm, "Area read only");
}
/**
* {@inheritDoc}
*/
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
JOptionPane.showMessageDialog(frm, "Area read only");
}
});
frm.add(new JScrollPane(area));
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.pack();
frm.setVisible(true);
}
}
You can add a KeyListener
to the text area, and in the keyPressed()
method do what you want, eg show a dialog. 您可以将
KeyListener
添加到文本区域,然后在keyPressed()
方法中执行所需的操作,例如显示一个对话框。
JTextArea ta = new JTextArea();
ta.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed, warn the user that this is read only!");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.