[英]Can't append text to a JTextArea from another class
Found a similar topic on here but the solutions provided didn't work (or I'm just not seeing it). 在这里找到了类似的主题,但是提供的解决方案不起作用(或者我只是看不到)。 Here's my code reduced to the minimum:
这是我的代码减少到最低限度:
Here's the class I want to call the print method from: 这是我要从中调用print方法的类:
{
HumanInterface gui = new HumanInterface();
gui.init();
gui.printToArea("from Main Class");
}
and here's the HumanInterface class which extends JFrame { 这是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);
}
});
}
When I call printToArea(...) from anywhere else than from within the HumanInterface class, it doesn't work. 当我从HumanInterface类中的其他地方调用printToArea(...)时,它不起作用。 What am I missing?
我想念什么?
The GUI you see is not the GUI you "want" to see, it's a second ;-) 您看到的GUI不是您“想要”看到的GUI,这是秒;-)
In your init()
function you create a second HumanInterface
: 在
init()
函数中,创建第二个HumanInterface
:
HumanInterface gst = new HumanInterface();
gst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gst.pack();
gst.setVisible(true);
I think you probably want that (not tested): 我认为您可能希望这样做(未经测试):
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.