Not showing graphics in JPanel which is added to another JPanel

前端 未结 1 1646
我在风中等你
我在风中等你 2020-12-04 03:07

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

相关标签:
1条回答
  • 2020-12-04 04:02

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题