2017-08-09 79 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

謝謝。但我仍然不明白爲什麼我需要一個構造函數。 –

相關問題