在这里找到了类似的主题,但提供的解决方案不起作用(或者我只是没有看到它)。这是我的代码减少到最少:
这是我想要从中调用打印方法的类:
{
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/