Muhammad Khan
Muhammad Khan

Reputation: 11

Panel wont show in the window

I am trying to start the program with jcheckbox hat selected and rectangle visible then the Rectangle disappears when the checkbox is unselected and repainted as checkbox is selected again. When I run the program and check the box another check box appears or left of the frame.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;

public class Head extends JPanel {

JCheckBox hat;

public Head() {
    hat = new JCheckBox("Hat");
    hat.setSelected(true);
    hat.addItemListener(new CheckSelection());

    add(hat);
}

class CheckSelection implements ItemListener {

    public void itemStateChanged(ItemEvent ie) {
        repaint();
    }
}


public void paintComponent(Graphics g) {

    setForeground(Color.RED);
    g.drawOval(110, 100, 100, 100);
    g.drawOval(130, 120, 20, 15);
    g.drawOval(170, 120, 20, 15);
    g.drawLine(160, 130, 160, 160);
    g.drawOval(140, 170, 40, 15);
    if (hat.isSelected()) {
        g.drawRect(100, 90, 120, 10);
    }
    }


 public static void main(String[] args) {
    Head head = new Head();
    JFrame f = new JFrame();
    f.add(head);
    f.setSize(400, 400);
    //f.setLayout(null);  
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

Upvotes: 0

Views: 28

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347194

You've broken the paint chain by not calling the paintComponent's super method

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    setForeground(Color.RED);
    g.drawOval(110, 100, 100, 100);
    g.drawOval(130, 120, 20, 15);
    g.drawOval(170, 120, 20, 15);
    g.drawLine(160, 130, 160, 160);
    g.drawOval(140, 170, 40, 15);
    if (hat.isSelected()) {
        g.drawRect(100, 90, 120, 10);
    } else {
        setForeground(Color.RED);
        g.drawOval(110, 100, 100, 100);
        g.drawOval(130, 120, 20, 15);
        g.drawOval(170, 120, 20, 15);
        g.drawLine(160, 130, 160, 160);
        g.drawOval(140, 170, 40, 15);
    }
}

The Graphics context is a shared resource between components, one of the jobs of paintComponent is to prepare the Graphics for painting, typically by filling it with the background color of the component. So failing to call super.paintComponent means that what ever was previously painted to the Graphics context will still be there

See Painting in AWT and Swing and Performing Custom Painting for more details about how painting works in Swing

Upvotes: 2

Related Questions