paintComponent overriding to draw on a panel

83 views Asked by At

This is a noob question. We are being taught applets in class, and I was trying something on my own.

The following is the code

import java.awt.*;
import javax.swing.*;


class controls extends JPanel{

@Override public void paintComponent(Graphics g) {
    g.drawOval(50, 50, 50, 50); // <-- draws an oval on the panel
}

}

 public class test extends JApplet{
public void init(){
    final JPanel stage = new JPanel();
    final JPanel controlPanel = new controls();
    final JPanel banner = new JPanel();
    final JLabel name = new JLabel("Test", JLabel.CENTER);
    this.setLayout(new BorderLayout());
    banner.setBackground(Color.CYAN);
    banner.add(name);
    this.add(controlPanel, BorderLayout.WEST);
    this.add(banner, BorderLayout.NORTH);
}
}

As far as I understand, paintComponent() need not be called explicitly. The controls class works well when used alone.

I mean the following code works.

public class test extends JApplet{
public void init(){
    JPanel controlPanel = new controls();
    this.add(controlPanel);
}
}

I am not able to understand the difference. Why does the same code work in this case, and not in the previous?

Thank you.

1

There are 1 answers

3
Paul Samsotha On BEST ANSWER

Override public Dimension getPreferredSize() (and return a new Dimension) in the controls class. When putting components in WEST the width will be determined by the preferredSize. If you don't override getPreferredSize, the preferred size will be 0. The CENTER will take up the rest of the space, after the WEST, ect is calculated. The second case works because it is in the CENTER of the default BorderLayout