正如標題所述,我想將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);
}
}
是的,非常感謝。這是一個錯誤。我只是糾正它,並再次測試,但仍然無法正常工作。我不認爲我的代碼中存在邏輯錯誤,是嗎? –
您是否保存更改並重新編譯,代碼在我的末端工作 – Arvind
我重新啓動了eclipse,之後它完美運行。不知道爲什麼,但你的答案確實解決了我的問題。謝謝你,小夥伴! –