检测JTextArea中的内容是否被修改
各位大大。我想要检测JTextArea的文本内容是否被修改了。怎么做。
[解决办法]
不太清楚你说的意思,可以对JTextArea内容的改变事件进行真挺,下面是我实现的例子将添加或者修改的内容在控制台回显
import java.awt.BorderLayout;import java.awt.Container;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JTextArea;import javax.swing.event.DocumentEvent;import javax.swing.event.DocumentListener;/** * * @author Administrator * */public class MyJTextAreaDemo1 extends JFrame{ private String checkedStr="清华大学"; private JTextArea textArea=null; private JLabel inputLabel=null; public MyJTextAreaDemo1(){} public MyJTextAreaDemo1(String title){ super(title); textArea=new JTextArea(5,10); inputLabel=new JLabel("input"); inputLabel.setLabelFor(textArea); Container container=this.getContentPane(); container.setLayout(new BorderLayout()); container.add(inputLabel,BorderLayout.EAST); container.add(textArea,BorderLayout.CENTER); textArea.getDocument().addDocumentListener(new DocumentListener(){ //不清楚這個方法监听的什么事件 @Override public void changedUpdate(DocumentEvent event) { // TODO Auto-generated method stub System.out.println("changedUpdate"); } @Override public void insertUpdate(DocumentEvent event) { // TODO Auto-generated method stub System.out.println(textArea.getText()); String inputStr=textArea.getText().trim(); if(inputStr.contains(checkedStr)){ JOptionPane.showMessageDialog(MyJTextAreaDemo1.this, "输出"); } } @Override public void removeUpdate(DocumentEvent event) { // TODO Auto-generated method stub System.out.println("removeUpdate"); } }); this.pack(); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); this.setVisible(true); } public static void main(String[] args){ new MyJTextAreaDemo1("Demo"); } }
[解决办法]
监听Plaint Document对象事件
[解决办法]
定义一个状态变量modified,在Document的事件处理中设为 true,文档保存后设为 false。
[解决办法]
保存 使用 DefaultEditorKit 提供的 write方法,自动处理了换行问题。