Reputation: 89
As the title describes, I want to Add JPanel from another class to JFrame in another class. However, the JFrame window will display, but not with JPanel. I'm sure the JPanel is not added into JFrame. Could you please tell me where goes wrong? Thank you so much!
JFrame Class:
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);
}
}
But if I code this this way, it actually works:
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);
}
}
Upvotes: 0
Views: 537
Reputation:
You have a typo error:
public class MyTank extends JPanel{
public void Paint(Graphics graphics){
^--- must be lower case
Upvotes: 1
Reputation: 468
You don't have a constructor specified for your MyTank class. While it is true that java provides you with a default no-arg constructor, this constructor usually doesn't do anything. In your case, while you do have a Paint
method, you still don't have any constructor.
I would suggest changing your JPanel class to look more like this:
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);
}
}
Upvotes: 0
Reputation: 2584
You're not specifying a layout for the 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);
}
}
Upvotes: 0