日期:2014-05-20 浏览次数:21269 次
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方法,自动处理了换行问题。