Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
316 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...