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);
}
}
Please do watch the constructor of the
MainClass, make this your habbit to follow the sequence as shown in this example. First add components to theJFramethen only make calls likepack(), setSize() or setVisible(...), not before that.Always make it your habbit, that whenever you override
paintcomponent()method, overridegetPreferredSize()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.