将另一个类的JPanel添加到另一个类的JFrame中

时间:2017-08-09 17:23:26

标签: java swing

正如标题所描述的,我想将另一个类的JPanel添加到另一个类的JFrame中。但是,JFrame窗口将显示,但不会显示JPanel。我确定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 CLass:

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);
}
}   

3 个答案:

答案 0 :(得分:1)

您有拼写错误:

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

答案 1 :(得分: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);
  }
}

答案 2 :(得分: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);
    }
}