Java 在JFrame内的JPanel上调用非静态方法

Java 在JFrame内的JPanel上调用非静态方法,java,swing,jframe,jpanel,Java,Swing,Jframe,Jpanel,我有一个JFrame,它在自己内部创建了一个JPanel类。在JPanel类中,我有一个函数,它绘制一个矩形,然后重新绘制区域,但是我无法访问JPanel并从main方法运行该方法 private static void createAndShowGUI() { //This is run by the main method JFrame f = new JFrame("Program Name"); f.setResizable(false); f.setDefaul

我有一个JFrame,它在自己内部创建了一个JPanel类。在JPanel类中,我有一个函数,它绘制一个矩形,然后重新绘制区域,但是我无法访问JPanel并从main方法运行该方法

private static void createAndShowGUI() { //This is run by the main method
    JFrame f = new JFrame("Program Name");
    f.setResizable(false);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    f.add(new MyPanel()); //I need to access this MyPanel that I just created.
    f.pack();
    f.setVisible(true);

    Utils.debug("Swing JFrame initialized."); // don't worry about this
    Utils.print("Initialization complete!"); //or this

    Utils.sleep(1.0); //or this

    //This is where I need to access the MyPanel class inside JFrame f.
} 

我在发布此消息后立即找到了解决方案

MyPanel panel = new MyPanel();
f.add(panel);

...

panel.method(args);

我将把它留在这里,这样如果其他任何人有这个问题,他们都可以看到。

我总是担心在事件调度线程上调用
sleep()
。程序的流程基本上在这一点上停止,所以这不是问题。我计划将程序设计成有点像KhanAcademy javascript程序,所有这些只是设置我的“画布”