正如标题所述,我想将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,之后它完美运行。不知道为什么,但你的答案确实解决了我的问题。谢谢你,小伙伴! –