Search code examples
javaswingjpaneljbuttonpaintcomponent

paintComponent is not erasing JPanel


The program is to display 3 buttons on the JPanel. The program is compiled successfully. The GUI Window then appears and is empty. When I minimise the window and then maximise it again the Buttons appear. On doing this again another set of Buttons appear. The button keeps on appearing when the window is refreshed and the older data is kept intact.

JPanel Class

class MyJPanel extends JPanel {
JButton jb1, jb2, jb3;

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, this.getWidth(), this.getHeight());
    jb1 = new JButton();
    jb2 = new JButton("Green");
    jb3 = new JButton("Blue");
    //g.drawString("Welcome!", 100, 100);
    ImageIcon img = new ImageIcon("next.png");
    jb1.setIcon(img);
    jb1.setToolTipText("Button 1");
    this.add(jb1);
    this.add(jb2);
    this.add(jb3);
}
}

JFrame Class

class MyJFrame extends JFrame {
MyJPanel mjp;

public MyJFrame(String title) {
    super(title);

    mjp = new MyJPanel();

    Container ct = getContentPane();
    ct.add(mjp);

    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Driver Class

class Gui5JButton {
public static void main(String[] args) {
    MyJFrame mjf = new MyJFrame("Prakhar");
    mjf.repaint();
}
}

Solution

  • paintComponent is called everytime your panel needs to be redraw, so everytime you minimize the window it will put the button again. If I understood what you want to do correctly, you need to remove the override and put this code :

    jb1 = new JButton();
    jb2 = new JButton("Green");
    jb3 = new JButton("Blue");
    //g.drawString("Welcome!", 100, 100);
    ImageIcon img = new ImageIcon("next.png");
    jb1.setIcon(img);
    jb1.setToolTipText("Button 1");
    this.add(jb1);
    this.add(jb2);
    this.add(jb3);
    

    in the constructor of your MyJPanel class.