[英]Can't append text to a JTextArea from another class
在这里找到了类似的主题,但是提供的解决方案不起作用(或者我只是看不到)。 这是我的代码减少到最低限度:
这是我要从中调用print方法的类:
{
HumanInterface gui = new HumanInterface();
gui.init();
gui.printToArea("from Main Class");
}
这是HumanInterface类,它扩展了JFrame {
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.