Swing - paintComponent method not being called

无人久伴 提交于 2019-11-28 08:02:39

问题


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 :)


回答1:


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.




回答2:


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) ;


来源:https://stackoverflow.com/questions/7398335/swing-paintcomponent-method-not-being-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!