Search code examples
javaswinginner-classespaintcomponent

paintComponent of inner class not called


Somebody would know to say me why my function paintComponent of the class PF is not called?

public class Fenetre
{

    private JFrame jframe;

    public Fenetre()
    {
        jframe = new JFrame(" works");
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jframe.setLayout(new BorderLayout());
        jframe.setLocationRelativeTo(null);
        jframe.setContentPane(new P());
        jframe.pack();
        jframe.setVisible(true);
    }

    public class P extends JComponent
    {
        public P()
        {
            this.setPreferredSize(new Dimension(WI,HI));
            this.add(new PF());
        }

        public class PA extends JComponent
        {
          @Override protected void paintComponent(Graphics g) {

                DrawX(g);
                DrawY(g);
            }

            public void DrawX(Graphics g)
            {
              \* .. */
            }

            public void DrawY(Graphics g)
            {
               \* ..*/
            }

        }

        public class PF extends PA
        {

            @Override protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                drawS(g);
                drawT(g);
            }

            public void drawS(Graphics g)
            { \* .. */
             }

            public void drawT(Graphics g)
            {
               \* ... */
            }

        }

It works when I set in the PF constructor the setSize function, but the setPreferredSize work too but not permit the class PF to be resizable, that's say if I resize my Jframe, the PF draw not resize ..

Hope someone could help me, thanks.


Solution

  • The likely issue is probably to do with the fact that PA and PF don't have a preferred size (the default being 0x0) and the fact that JComponent by default has no layout manager

    The paint sub system has determined that the child components don't need to be painted as they are, technically, not visible on the screen

    Start by setting the the layout manager of P and overriding the getPreferredSize method of PA.

    It is very important that you alway call super.paintComponent when wever your override the method. This is doubly important when you are dealing with transparent components like JComponent as this will introduce very nasty paint artifacts if you don't