首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

检测JTextArea中的内容是否被修改,该如何解决

2012-01-12 
检测JTextArea中的内容是否被修改各位大大。我想要检测JTextArea的文本内容是否被修改了。怎么做。[解决办法]

检测JTextArea中的内容是否被修改
各位大大。我想要检测JTextArea的文本内容是否被修改了。怎么做。

[解决办法]
不太清楚你说的意思,可以对JTextArea内容的改变事件进行真挺,下面是我实现的例子将添加或者修改的内容在控制台回显

Java code
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方法,自动处理了换行问题。

热点排行