2017-08-09 92 views
0

正如标题所述,我想将JPanel从另一个类添加到另一个类中的JFrame。但是,JFrame窗口将显示,但不会与JPanel一起显示。我确定JPanel不会被添加到JFrame中。你能告诉我哪里出了问题吗?非常感谢!将另一个类的JPanel添加到另一个类的JFrame中

JFrame类:

public class Test extends JFrame{ 
    MyTank myTank = null; 
    public static void main(String[] args) { 
    new Test(); 
    } 

public Test(){ 
    myTank = new MyTank(); 
    add(myTank); 
    setSize(400, 400); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setVisible(true); 
    } 
} 

JPanel类:

public class MyTank extends JPanel{ 
    public void paint(Graphics graphics){ 
    super.paint(graphics); 
    graphics.setColor(Color.YELLOW); 
    graphics.fill3DRect(50,50, 50, 50, true); 
    } 
} 

但如果我这样这样的代码,它的实际工作:

public class myFrameExample extends JFrame{ 
myPanel2 mPanel = null; 
MyTank myTank = null; 
public static void main(String[] args) { 
    myFrameExample myTankShape = new myFrameExample(); 
} 

public myFrameExample(){ 
    mPanel = new myPanel2(); 
    this.add(mPanel); 
    this.setSize(500, 500); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    this.setVisible(true); 
} 
} 

class myPanel2 extends JPanel{ 
public void paint(Graphics graphics){ 
    super.paint(graphics); 
    graphics.setColor(Color.BLACK); 
    graphics.drawOval(10, 10, 50, 50); 
    graphics.fillOval(50, 50, 40, 40); 
} 
} 

回答

1

你有一个错字错误:

public class MyTank extends JPanel{ 
    public void Paint(Graphics graphics){ 
       ^--- must be lower case 
+0

是的,非常感谢。这是一个错误。我只是纠正它,并再次测试,但仍然无法正常工作。我不认为我的代码中存在逻辑错误,是吗? –

+0

您是否保存更改并重新编译,代码在我的末端工作 – Arvind

+0

我重新启动了eclipse,之后它完美运行。不知道为什么,但你的答案确实解决了我的问题。谢谢你,小伙伴! –

0

你不指定布局对于JFrame:

public class Test extends JFrame{ 
    MyTank myTank = null; 
    public static void main(String[] args) { 
    new Test(); 
    } 

public Test(){ 
    myTank = new MyTank(); 
    //setting the layout to null, you can use other layout managers for this 
    setLayout(null); 
    add(myTank); 
    setSize(400, 400); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setVisible(true); 
    } 
} 
+0

这不要紧,因为默认布局的FlowLayout。您不需要指定布局。 –

0

您没有为MyTank类指定的构造函数。尽管java为您提供了一个默认的无参数构造函数,但这个构造函数通常不会做任何事情。在你的情况下,虽然你有一个Paint方法,你仍然没有任何构造函数。

我建议改变你的JPanel类看起来更像这样:

public class MyTank extends JPanel { 
    public MyTank { 
     //insert your code here, and possibly call your `Paint` method. 
    } 
    public void Paint(Graphics graphics){ 
     super.paint(graphics); 
     graphics.setColor(Color.YELLOW); 
     graphics.fill3DRect(50,50, 50, 50, true); 
    } 
} 
+0

谢谢。但我仍然不明白为什么我需要一个构造函数。 –

相关问题