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



正如标题所描述的,我想将另一个类的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);
}
}   

您有一个拼写错误:

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

您没有为 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);
}
}

您没有为 MyTank 类指定构造函数。虽然 java 确实为您提供了一个默认的 no-arg 构造函数,但这个构造函数通常不做任何事情。在您的情况下,虽然您确实有一个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);
}
}

最新更新