java - 无法将文本从另一个类追加到 JTextArea

标签 java swing reference jtextarea

在这里找到了类似的主题,但提供的解决方案不起作用(或者我只是没有看到它)。这是我的代码减少到最少:

这是我想要从中调用打印方法的类:

{
    HumanInterface gui = new HumanInterface();
    gui.init();
    gui.printToArea("from Main Class");
}

这是扩展 JFrame 的 HumanInterface 类 {

JTextArea area = createArea();

public void init() throws InvocationTargetException, InterruptedException
{
    HumanInterface gst = new HumanInterface();
    gst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gst.pack();
    gst.setVisible(true);

    printToArea("print from HumanInterface class");
}

public HumanInterface() throws InvocationTargetException,
        InterruptedException
{
    Container container = getContentPane();
    container.setLayout(new GridLayout(2, 3));

    container.add(new JScrollPane(area));
}

public void printToArea(String string)
{
    try
    {
        updateArea(area, string);
    }
    catch (InvocationTargetException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (InterruptedException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

private JTextArea createArea()
{
    final JTextArea area;
    area = new JTextArea();
    area.setBackground(Color.GRAY);

    return area;
}

private void updateTextArea(final JTextArea textArea, final String string)
        throws InvocationTargetException, InterruptedException
{
    SwingUtilities.invokeAndWait(new Runnable()
    {
        @Override
        public void run()
        {
            textArea.append(string);
        }
    });

}

当我从 HumanInterface 类中以外的任何地方调用 printToArea(...) 时,它不起作用。我错过了什么?

最佳答案

您看到的 GUI 不是您“想要”看到的 GUI,它是第二个 ;-)

init() 函数中,您创建第二个 HumanInterface:

HumanInterface gst = new HumanInterface();
gst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gst.pack();
gst.setVisible(true);

我想你可能想要这个(未经测试):

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);

关于java - 无法将文本从另一个类追加到 JTextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23154522/

相关文章:

java - 获取网页时防止应用程序挂起

java - 如果鼠标位于框架内,如何使框架可见,而当鼠标不在 Java 中时,如何使框架不可见?

c++ - 为什么可以重新设置引用参数?

c++ - `this == &x` 是确定指针 (this) 和引用 (x) 是否指向同一对象的正确方法吗?

c++ - 为什么非常量引用参数可以绑定(bind)到临时对象?

java - 我如何测量有多少线程正在执行一段代码?

java - Drools API 混淆

java - 主类中未调用 ActionListener?

java - 如何从数组中打印出对象?

java - 将 jtable 居中对齐到 jscrollpane