当我在jtextarea中打开文件时。我使用textArea.setEditable(false)将textarea设置为不可编辑,但是当我按下键时,如何在jpanel文件中显示消息是只读的。
谢谢。
答案 0 :(得分:1)
不要使用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);
}
}
答案 1 :(得分:0)
您可以在文本区域添加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!");
}
});