Search code examples
javaswingjpanelpaintcomponent

Not showing graphics in JPanel which is added to another JPanel


When adding a JPanel that has graphics to a JFrame, it's working fine. But when I try to add a JPanel in which I have added another JPanel with graphics, its not showing in the JFrame. Please see code below

package sample;

import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame{
    public static void main(String[] args) {
        new Main();
    }

    public Main(){
        setTitle("Sample");
        setVisible(true);
        setSize(500,500);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        add(new SamplePanel2());
    }
}

class SamplePanel2 extends JPanel{
    public SamplePanel2(){
        add(new JButton("Hi"));
        add(new SamplePanel());
    }
}
class SamplePanel extends JPanel {
    public SamplePanel(){
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString("HHHHHHHHHHHH", 100, 100);
    }
}

Solution

  • Please do watch the constructor of the Main Class, make this your habbit to follow the sequence as shown in this example. First add components to the JFrame then only make calls like pack(), setSize() or setVisible(...), not before that.

    Always make it your habbit, that whenever you override paintcomponent() method, override getPreferredSize() method as well.

    And always put calls like pack()/setVisible(...) inside the EDT - Event Dispatch Thread. Please read Concurrency in Swing, for more detail on the topic.

    import java.awt.Dimension;
    import java.awt.Graphics;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class Main extends JFrame{
        public static void main(String[] args) {
            new Main();
        }
    
        public Main(){
            setTitle("Sample");        
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setContentPane(new SamplePanel2());
            pack();        
            setVisible(true);
        }
    }
    
    class SamplePanel2 extends JPanel{
        public SamplePanel2(){
            add(new JButton("Hi"));
            add(new SamplePanel());
        }
    }
    class SamplePanel extends JPanel {
        public SamplePanel(){
        }
    
        @Override
        public Dimension getPreferredSize()
        {
            return (new Dimension(300, 300));
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawString("HHHHHHHHHHHH", 100, 100);
        }
    }