Search code examples
javaswingjframejlabel

unable to draw on JFrame


I am trying to draw something on a JFrame

public class Frame extends JFrame{
    public static final int US=0;
    public static final int GERMANY=1;
    public Frame() {
        super("Frame");
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setContentPane(new JPanel());
        this.setSize(800, 600);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
    public void draw() {
        this.removeAll();
        int count;
        JPanel Panel = new JPanel();
        GridLayout layout=new GridLayout(0, 1);
        Panel.setLayout(layout);
        JLabel label2 = new JLabel("Text-Only Label");
        Panel.add(label2);
        this.getContentPane().add(Panel);
        this.validate();
        this.repaint();
    }

}

When I try to call draw() from another class, the JFrame doesn't update.

It is still a blank screen as seen in constructor.

any help would be appreciated.


Solution

  • Try this:

    public void draw() {
                this.getContentPane().removeAll();
                int count;
                JPanel Panel = new JPanel();
                GridLayout layout=new GridLayout(0, 1);
                Panel.setLayout(layout);
                JLabel label2 = new JLabel("Text-Only Label");
                Panel.add(label2);
                this.getContentPane().add(Panel);
                this.validate();
                this.repaint();
            }