Search code examples
javaswingpaintcomponent

Why components are not visible after use paint method to parent


I created a JDesktopPane object as an inner class and I used the @Override paint method to `JDesktopPane. after I did it now I could,t add any components to it (Components are not visible). why it isn't work

import javax.swing.*;
import java.awt.*;

public class Example {
    public static void main(String[] args){
        JFrame frame = new JFrame("Test");
        frame.setSize(500,500);
        frame.setVisible(true);

        JDesktopPane pane = new JDesktopPane(){
            public void paint(Graphics g){
                
            }
        };
        frame.add(pane);

        JInternalFrame inf = new JInternalFrame();
        inf.setVisible(true);
        inf.setSize(100,100);
        pane.add(inf);
    }
}

Solution

  • Because you should not @Override paint() method. You should override paintComponent() method instead. You should also call super.paintComponent() in that method in order to respect the paint chain.

    You can find more information about custom painting in Swing's documentation.

    I also don't recommend you to extend a JDesktopPane. Desktop panes are meant to be top level containers that usually stand as host for other components. With other words, keep the JDesktopPane just a JDesktopPane and then create a JPanel with the overriden paintComponent(). Finally, add this panel to the desktop pane.