2

I have created two classes in my package named ball and toop . and want to add them in my third class whitch extends JFrame . I did but objects didnt display in a JFrame when I use Container . and without Container only one of them added to JFrame . here is my code :

package mytry;

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class trypanel extends JFrame {
JFrame frame = new JFrame();
Container panel = new Container();
public trypanel(){
    toop c = new toop();
    ball a = new ball(20,20,1);
    frame.setVisible(true);
    frame.setSize(550,550);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    panel.add(c);
    panel.add(a);
    frame.getContentPane().add(panel);
    c.run();

}
}

How can I add my classes to the JFrame ??

1 Answer 1

1

Since your class extends JFrame this line should be removed:

JFrame frame = new JFrame();

This means that all the references to frame should be removed as well, or changed to this.

Instead on using Container you want to use JPanel, so change this line:

Container panel = new Container();

to

JPanel panel = new JPanel();

and add the panel to the frame in the constructor like this:

this.add(panel);

instead of using frame.getContentPane().add(panel);

That should work, even though I haven't tried your code.

You might also want to use a LayoutManager with the JPanel to ensure the correct layout of things.

Sign up to request clarification or add additional context in comments.

8 Comments

thank you so much may i ask you another question ? when i have define two objects from my ball class and toop class , how can i add them to my JFrame ? when i use frame.add() , the second one replace the other .
You add the objects to the panel with panel.add(objectReference) and add the panel to the frame with this.add(panel) and then the first should not be replaced be the second if you use different variable names for the two objects.
public trypanel(){ toop c = new toop(20,320); ball a = new ball(20,320,1); setVisible(true); setSize(550,550); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel.add(c); panel.add(a); this.add(panel); } but nothing dispalyed :(( what should i do ?
Without knowing how toop and ball are implemented it's hard to say why they don't show. Do they extend JPanel or some graphic object and if so do they override paintComponent?
yes i use paint(Graphics g) in both classes . is this making a trouble ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.