/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package texteditor;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
/**
*
* @author
*/
public class TextPad implements DocumentListener,ChangeListener{
private JTextPane textArea;
private Document textDoc;
private int selectionOffset;
private int selectionLength;
public void init()
{
//System.out.println("Constructor invoked");
// TODO code application logic here
JFrame window = new JFrame("Text Editor");
//JMenuBar menuBar = window.getJMenuBar();
/**
//Create menu bar
JMenuBar menuBar= new JMenuBar();
//File Menu
JMenu fileMenu = new JMenu("File");
fileMenu.add(new JMenuItem("Save"));
* */
// menuBar.add(fileMenu);
//window.setJMenuBar(menuBar);
this.textArea= new JTextPane();
this.textDoc = this.textArea.getDocument();
this.textDoc.addDocumentListener(this);
this.textArea.getCaret().addChangeListener(this);
//System.out.println(d.getClass());
//override default text generation ****THIS LINE******
((AbstractDocument)this.textDoc).getDocumentFilter();
//Add scorllable interface in jtextpane
window.add(new JScrollPane(this.textArea));
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public void changedUpdate(DocumentEvent e)
{
//System.out.println("changed");
}
public void removeUpdate(DocumentEvent e)
{
System.out.println("removed");
}
public void insertUpdate(DocumentEvent e)
{
try
{
System.out.println(this.textDoc.getText(0,this.textDoc.getLength()));
}
catch(Exception ex)
{
System.err.println(ex);
}
}
/**
*
* @param e
*/
public void stateChanged(ChangeEvent e)
{
System.out.println(this.textArea.getCaret().getMark());
}
}
为什么强制转换为abstractDocument
as((AbstractDocument)this.textDoc).getDocumentFilter();
有效,但没有强制转换它
this.textDoc.getDocumentFilter();
会引发找不到方法的错误。谁能解释一下?
编辑:
if(this.textDoc instanceof AbstractDocument)
{
System.out.println("Yes it is");
}
printsYes it is
这也暗示它是一种AbstractDocument
. 我不明白为什么调用AbstractDocument
抛出错误的方法。