Search code examples
javaswingobjectmethodsjtextpane

How to add method to JTextPane


I want to create a JEditorPane with a custom method.
A method which appends new colored text to the pane.

Code :

console = new JTextPane() {
    public void append() {
        //*****
    }
};
console.append();

But eclipse says the method is never used and throws an error when I try to call it... am I doing something wrong?

Adding the method to the object will make it much more efficient... thanks to helpers!


Solution

  • You cannot invoke append() because console relies on the JTextPane type not the anonymous class where you defined append().

    To invoke append() outside the anonymous class, you have to create a subclass of JTextPane.
    If it makes sense, you could define it a private static class member of the current class :

    ...
    private static class MyTextPane extends JTextPane {
    
       public void append() {
        // your code
      }
    }
    ...
    MyTextPane myTextPane = new MyTextPane();
    myTextPane.append();