JayMuzie
JayMuzie

Reputation: 341

Swing - paintComponent method not being called

i simply implemented class that inherits JPanel like below

public class Orpanel extends JPanel {

....
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        g2d.setPaint(tpaint);
        g2d.fill(rect); 
    }
....
}

class Orpanel is loading image and adjusting it's own size.

here's question.

Calling JFrame's setContentpane(Orpanel's instance) makes it works fine but when i attach Orpanel to JFrame calling add() method instead of setContentpane (i know setcontentpane is not meaning attach.. anyway), it dosen't work.

finally figured out when i used add() method, Component that was added to JFrame doesn't call paintComponent() method. even though i call repaint() method manually, still paintComponent() method is not called.

did i miss something? any help will be appreciated!

thx in advance. Jaeyong shin.


i added extra code.

public Test(OwPanel op) 
{
    super();
    Dimension monitor = Toolkit.getDefaultToolkit().getScreenSize();
    op.setBackground(Color.white);
    this.setBackground(Color.white);        
    this.setBounds(monitor.width / 2 - 200 , monitor.height / 2 - 200, 400, 400);       
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setTitle("test");      
    this.setLayout(null);
    this.getContentPane().add(op);
    //this.setContentPane(op);
    this.setVisible(true);
    this.validate();
}

    public static void main(String[] args) {
    // TODO Auto-generated method stub

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            OwPanel op = new OwPanel("d:\\java_workplace\\img\\img1.jpg", 100, 100);
            OwLabel ol = new OwLabel("d:\\java_workplace\\img\\img2.jpg", 300, 50);
            Test tst =  new Test(op);
            tst.add(ol);
        }
    });

still doesn't work if setContentpane() method replaced to getContentpane().add(). don't be confused. Owpanel and Orpanel is same :)

Upvotes: 5

Views: 6995

Answers (2)

jfpoilpret
jfpoilpret

Reputation: 10519

In your sample code, I see you have chosen NOT to use a LayoutManager, that's a very bad idea, but anyway, sicne you go this way, I see one reason for your Orpanel.paintComponent() not being called: it is probably not visible inside the frame!

If you have no LayoutManager, then you must explicitly set the size and location (through setBounds()) of all components you add to the frame.

It is likely you didn't do it, hence the size of Orpanel instance is probably 0 hence it never gets painted.

Upvotes: 5

Rune Aamodt
Rune Aamodt

Reputation: 2611

Sounds like you're just using the wrong methods. You should be doing this when adding a panel to a frame:

frame.getContentPane().add(panel) ;

Upvotes: 0

Related Questions