0

在扩展JEditorPane的子类中设置新文本时遇到问题。IndexJFrame

package gui;
...
public class Index extends JFrame {
    JEditorPane editorPaneMR = new JEditorPane();

public static void main(String[] args) {
    ...
}

public Index() {
        JButton SearchButton = new JButton("OK");
        SearchButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                parser GooBlog = new parser(url);
                try {
                    GooBlog.hello(); // Go to subclass parser
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

这就是称为解析器的子类的代码

package gui;
public class parser extends Index{
    String url;

    public parser (String urlInput){
        this.url = urlInput;
    }

    public void hello () throws IOException{
        editorPaneMR.setText("Hello World");
    }
}

问题是当我按下确定按钮时,它没有在 JEditorPane 中显示文本“Hello world”!它没有向我显示任何错误,只是没有发生任何事情。

4

1 回答 1

1

代码行

parser GooBlog = new parser(url);

不仅实例化一个解析器,还实例化一个新的Index/ JFrame。这个JEditorPane新创建JFrame的 用于内部方法hello,并且由于框架不可见,因此不会发生任何事情。

一个解决方案可能是为您的方法JFrameJEditorPane方法提供参考hello,例如

public class Parser {  // does no longer extend Index
    String url;

    public Parser(String urlInput) {
        this.url = urlInput;
    }

    public void hello(JEditorPane editorPane) {  // has argument now
        editorPane.setText("Hello World");
    }
}

然后将通过

Parser gooBlog = new Parser(url);
gooBlog.hello(Index.this.editorPaneMR);

注意:请遵守常见的 Java 编码标准,并为类使用大写名称,即Parser代替parser,以及小写变量/字段/方法名称,例如gooBlog.

于 2013-05-07T17:50:53.640 回答