java – Why isn't the dotted line drawn on the JPanel?

Question:

public MainFrame() {                                    //конструктор
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 800, 800);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JPanel menuPanel = new JPanel();
    menuPanel.setBackground(Color.LIGHT_GRAY);
    menuPanel.setBounds(10, 11, 250, 751);
    contentPane.add(menuPanel);

    gamePanel = new JPanel();
    gamePanel.setForeground(Color.WHITE);
    gamePanel.setBackground(Color.WHITE);
    gamePanel.setBounds(270, 11, 512, 751);
    gamePanel.setLayout(null);
    contentPane.add(gamePanel);

    ImageLabel imgLabel = new ImageLabel(gamePanel.getWidth(), gamePanel.getHeight());
    gamePanel.add(imgLabel);

}

ImageLabel class:

public class ImageLabel extends JLabel {

private int width, height;

public ImageLabel(int width, int height){
    super("label");
    this.width = width;
    this.height = height;
}

@Override
public void paint(Graphics g) {
    super.paint(g); 
    Graphics2D f = (Graphics2D) g;
    f.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, new float[]{10f, 5f}, 0f));
    f.setColor(Color.RED);
    f.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    f.drawLine(0, 0, width , height);
}

}

Why isn't the line drawn on the JPanel?

Answer:

You haven't set the dimensions of the ImageLabel . Therefore, width , height will be equal to zero. You have two options, add a layer manager to the gamePanel, or set the size of the imgLabel element manually using setBounds() (as @zRrr correctly said).

First:

gamePanel.setLayout(new BorderLayout());

Second:

imgLabel.setBounds(0, 0, 100, 100);
Scroll to Top