在这里找到类似的主题,但提供的解决方案不起作用(或者我只是没有看到它)。这是我的代码减少到最低限度:
这是我想从以下方法调用print方法的类:
{
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(...)时,它不起作用。我错过了什么?
答案 0 :(得分:1)
您看到的GUI不是您想要的GUI#34;看,它是第二个; - )
在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);