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.
Override
public Dimension getPreferredSize()
(and return anew Dimension
) in thecontrols
class. When putting components inWEST
the width will be determined by the preferredSize. If you don't overridegetPreferredSize
, the preferred size will be 0. TheCENTER
will take up the rest of the space, after theWEST
, ect is calculated. The second case works because it is in theCENTER
of the defaultBorderLayout