/*
* 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
强制转换为((AbstractDocument)this.textDoc).getDocumentFilter();
却不能像这样强制转换this.textDoc.getDocumentFilter();
确实抛出无法找到方法的错误。谁能解释一下?编辑:
if(this.textDoc instanceof AbstractDocument)
{
System.out.println("Yes it is");
}
打印
Yes it is
,这也意味着它是AbstractDocument
的一种。我不明白,为什么AbstractDocument
的调用方法会引发错误。 最佳答案
HoverCraft正确。使用Java,您只能根据其转换方式访问对象的方法和属性。因此,以证明
public interface Fooer {
public int doFoo();
}
public class Foo implements Fooer{
public int doFoo(){return 0;}
public void doNoFooer(){}
}
public class Bar extends Foo {
public void doYesFooer(){}
}
如果使用这些定义,将会发生以下情况:
Foo foo = new Bar();
foo.doNoFooer(); // fine because it is a method of Foo
foo.doFoo();
foo.doYesFooer(); // causes an error because the variable is improperly typed.
Fooer fooer = foo;
fooer.doFoo(); // find because it is part of the definition of Fooer
fooer.doYesFoo(); // causes an error because the variable is improperly typed.
fooer.doNoFoo(); // causes an error because the variable is improperly typed.
Bar bar = (Bar) foo;
// notice that the next three do not cause errors.
bar.doYesFooer();
bar.doNoFooer();
bar.doFoo();